package com.apes.fn.scm.retailOrder.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.report.repository.SalesReportDao;
import com.apes.fn.scm.retailOrder.repository.ReportDaliyDao;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.Arith;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.pi.repository.TimestampRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apestech.framework.json.JSON;
import com.apestech.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 功能：
 *
 * @author zhuyh
 * @time 15:19
 * @date 2020/6/20
 */
@Service("rclDaliyReportService")
public class RclDaliyReportService extends DomainService {

    @Autowired
    ReportDaliyDao reportDaliyDao;
    @Autowired
    TimestampRepository timestampRepository;
    @Autowired
    DeptRepository deptRepository;

    /**
     * 传入yyyy-mm-dd格式的时间字串，返回JAVA的日期类型
     * @param sDate
     * @return
     * @throws Exception
     */
    private Date strToDate(String sDate) throws Exception{
        if(sDate.indexOf(" ")>=0){
            sDate=sDate.substring(0,sDate.indexOf(" ")).trim();
        }
        String DateList[]=sDate.split("-");
        String strMM = String.format("%02d",Integer.parseInt(DateList[1]));
        String strDD = String.format("%02d",Integer.parseInt(DateList[2]));
        String strDate=DateList[0]+'-'+strMM+'-'+strDD;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = (Date) sdf.parse(strDate);
        return date;
    }

    /**
     * 将传入的JAVA时间格式，返加JAVA不带时间点格式的变量
     * @param date
     * @return
     * @throws Exception
     */
    private Date getDate(Date date) throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(date);
        return strToDate(dateString);
    }


    /**
     * 获取不带时间点的当前日期，返回JAVA类型变量
     * @return
     * @throws Exception
     */
    public Date getNowDate() throws Exception {
        Date currentTime = new Date();
        return getDate(currentTime);
    }


    /**
     * 获取加减后的时间
     *
     * @param date
     * @param day
     * @return
     * @throws Exception
     */
    private Date addOrReduceTime(Date date, int day) throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, day);//-1今天的时间加一天

        Date dateNeed = calendar.getTime();
        return getDate(dateNeed);
    }

    /**
     * 定时任务,销售日月报表
     */
    public void rclDAILYSALESREPORT() throws Exception {

        Date currentTime = getNowDate();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date date = addOrReduceTime(currentTime, -1);
        String sDate = sdf.format(date);
        Date datenew = sdf.parse(sDate);


        EntityManager entityManager = SpringManager.getBean(EntityManager.class);
        Query query = entityManager.createNativeQuery("{call SUM_RCL_DAILYSALESREPORT(?)}")
                .setParameter(1, datenew);
        int count = query.executeUpdate();
        System.out.println("----------------:" + count);
    }


    /**
     * 定时任务,销售日月报表,实时报表
     */
    public void rclDAILYSALESREPORTReal() throws Exception {
        Date currentTime = getNowDate();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date date = addOrReduceTime(currentTime, 0);
        String sDate = sdf.format(date);
        Date datenew = sdf.parse(sDate);

        EntityManager entityManager = SpringManager.getBean(EntityManager.class);
        Query query = entityManager.createNativeQuery("{call SUM_RCL_DAILYSALESREPORT(?)}")
                .setParameter(1, datenew);
        int count = query.executeUpdate();
        System.out.println("----------------:" + count);
    }


    /**
     * 定时任务,会员联盟日报表,实时报表
     */
    public void rclVipUnionReport() throws Exception {
        Date currentTime = getNowDate();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date date = addOrReduceTime(currentTime, 0);
        String sDate = sdf.format(date);
        Date datenew = sdf.parse(sDate);


        EntityManager entityManager = SpringManager.getBean(EntityManager.class);
        Query query = entityManager.createNativeQuery("{call SUM_VIP_UNION_REPORT(?)}")
                .setParameter(1, datenew);
        int count = query.executeUpdate();
        System.out.println("----------------:" + count);
    }


    /**
     * 定时任务,销售毛利报表
     */
    public void rclGrossProfitOnSales() throws Exception {
        Date currentTime = getNowDate();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = addOrReduceTime(currentTime, -1);
        String sDate = sdf.format(date);
        Date datenew = sdf.parse(sDate);
        EntityManager entityManager = SpringManager.getBean(EntityManager.class);
        Query query = entityManager.createNativeQuery("{call SUM_GROSS_PROFIT_ON_SALES(?)}")
                .setParameter(1, datenew);
        int count = query.executeUpdate();
        System.out.println("----------------:" + count);
    }

    /**
     * 定时任务,销售明细报表,实时报表
     */
    public void rclSaleReport() throws Exception {
        Date currentTime = getNowDate();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = addOrReduceTime(currentTime, 0);
        String sDate = sdf.format(date);
        Date datenew = sdf.parse(sDate);
        EntityManager entityManager = SpringManager.getBean(EntityManager.class);
        Query query = entityManager.createNativeQuery("{call SUM_SALE_REPORT(?)}")
                .setParameter(1, datenew);
        int count = query.executeUpdate();
        System.out.println("----------------:" + count);
    }

    /**
     * 定时任务,权责发生制,实时报表
     */
    public void rclAccrualBasis() throws Exception {
        Date currentTime = getNowDate();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = addOrReduceTime(currentTime, 0);
        String sDate = sdf.format(date);
        Date datenew = sdf.parse(sDate);
        EntityManager entityManager = SpringManager.getBean(EntityManager.class);
        Query query = entityManager.createNativeQuery("{call SUM_ACCRUAL_BASIS(?)}")
                .setParameter(1, datenew);
        int count = query.executeUpdate();
        System.out.println("----------------:" + count);
    }

    /**
     * 定时任务,收付实现制,实时报表
     */
    public void rclCashBasis() throws Exception {
        Date currentTime = getNowDate();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = addOrReduceTime(currentTime, 0);
        String sDate = sdf.format(date);
        Date datenew = sdf.parse(sDate);
        EntityManager entityManager = SpringManager.getBean(EntityManager.class);
        Query query = entityManager.createNativeQuery("{call SUM_CASH_BASIS(?)}")
                .setParameter(1, datenew);
        int count = query.executeUpdate();
        System.out.println("----------------:" + count);
    }


    /***
     * 查询销售日报数据
     */
    public JSONObject findRCL_DAILYSALESREPORT(SimpleRequest request) throws Exception {
        JSONObject param = request.getJO();

        JSONObject objDate = new JSONObject();
        Date strarD = param.getDate("STARTDATEs");
        Date strarE = param.getDate("ENDDATEs");

        Date date = addOrReduceTime(strarE, 0);//时间加减
        if (param.get("DEPTID") != null) {
            param.put("COMPANYID", deptListGetCompanyIds(param));
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String sStartDate = sdf.format(strarD);
        String sEndDate = sdf.format(date);

        Date startDate = sdf.parse(sStartDate);
        Date endDate = sdf.parse(sEndDate);

        param.put("STARTDATE", startDate);
        param.put("ENDDATE", endDate);
        param.put("merge", "1");

        //获取查询数据
        JSONArray array = reportDaliyDao.findRCL_DAILYSALESREPORT(param);
        JSONArray result = new JSONArray();
        array.forEach(data -> {
            JSONObject resultData = new JSONObject();
            JSONObject object = (JSONObject) data;
            resultData.put("DATE_OF_STATISTICS", object.get("DATE_OF_STATISTICS"));
            if (param.get("COMPANYID") != null) {
                resultData.put("COMPANY_ID", object.get("COMPANY_ID"));
                resultData.put("COMPANY_NAME", object.get("COMPANY_NAME"));
            } else {
                resultData.put("COMPANY_NAME", "赋能公司");
            }
            if (param.get("DEPTID") != null) {
                resultData.put("DEPT_ID", object.get("DEPT_ID"));
                resultData.put("DEPT_NAME", object.get("DEPT_NAME"));
            }

            result.add(matchResult(object, resultData, this::processDataDay));
        });
        if (param.get("DEPTID") != null) {
            objDate.put("DAILYlIST", result);
        } else {
            JSONArray resultStatistics = new JSONArray();
            resultStatistics.add(matchResultStatistics(array, new JSONObject(), this::processDataStatistics));
            objDate.put("DAILYlIST", resultStatistics);
        }


        return objDate;
    }

    private List<String> deptListGetCompanyIds(JSONObject param) {
        List<Dept> depts = deptRepository.findAll(JpaDsl.toCriteria("id", "IN", param.get("DEPTID")));
        return depts.stream().map(dept -> dept.getCompany().getId()).distinct().collect(Collectors.toList());
    }


    /***
     * 查询销售日报数据,每日数据
     */
    public JSONObject findRCL_DAILYSALESREPORT_ALL(SimpleRequest request) throws Exception {
        JSONObject param = request.getJO();

        JSONObject objDate = new JSONObject();

        Date strarD = param.getDate("STARTDATEs");
        Date strarE = param.getDate("ENDDATEs");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


        Date date = addOrReduceTime(strarE, 0);//时间加减

        if (param.get("DEPTID") != null) {
            param.put("COMPANYID", deptListGetCompanyIds(param));
        }


        String sStartDate = sdf.format(strarD);
        String sEndDate = sdf.format(date);

        Date startDate = sdf.parse(sStartDate);
        Date endDate = sdf.parse(sEndDate);

        param.put("STARTDATE", startDate);
        param.put("ENDDATE", endDate);
        param.put("merge", "1");

        //获取查询数据
        JSONArray array = reportDaliyDao.findRCL_DAILYSALESREPORT_ALL(param);
        JSONArray result = new JSONArray();
        array.forEach(data -> {
            JSONObject resultData = new JSONObject();
            JSONObject object = (JSONObject) data;
            if (param.get("COMPANYID") != null) {
                resultData.put("COMPANY_ID", object.get("COMPANY_ID"));
                resultData.put("COMPANY_NAME", object.get("COMPANY_NAME"));
            } else {
                resultData.put("COMPANY_NAME", "赋能公司");
            }
            if (param.get("DEPTID") != null) {
                resultData.put("DEPT_ID", object.get("DEPT_ID"));
                resultData.put("DEPT_NAME", object.get("DEPT_NAME"));
            }
            result.add(matchResult(object, resultData, this::processDataDay));
        });
        if (param.get("DEPTID") != null) {
            objDate.put("DAILYlIST", result);
        } else {
            JSONArray resultStatistics = new JSONArray();
            Map<Date, List<Object>> map = array.stream().collect(Collectors.groupingBy(x -> ((JSONObject) x).getDate("DATE_OF_STATISTICS")));
            map.forEach((k, v) -> {

                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("DATE_OF_STATISTICS", k.getTime());
                    resultStatistics.add(matchResultStatistics(JSONArray.parseArray(JSON.toJSONString(v)), jsonObject, this::processDataStatistics));
                } catch (Exception e) {
                    e.printStackTrace();
                }

            });
            objDate.put("DAILYlIST", resultStatistics);
        }


        return objDate;
    }

    /***
     * 查询销售日报数据,汇总
     */
    public JSONObject findRCL_DAILYSALESREPORT_ALL_DATE(SimpleRequest request) throws Exception {
        JSONObject param = request.getJO();

        JSONObject objDate = new JSONObject();

        Date strarD = param.getDate("STARTDATEs");
        Date strarE = param.getDate("ENDDATEs");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


        Date date = addOrReduceTime(strarE, 0);//时间加减

        if (param.get("DEPTID") != null) {
            param.put("COMPANYID", deptListGetCompanyIds(param));
        }


        String sStartDate = sdf.format(strarD);
        String sEndDate = sdf.format(date);

        Date startDate = sdf.parse(sStartDate);
        Date endDate = sdf.parse(sEndDate);

        param.put("STARTDATE", startDate);
        param.put("ENDDATE", endDate);
//        param.put("merge", "1");

        //获取查询数据
        JSONArray array = reportDaliyDao.findRCL_DAILYSALESREPORT_ALL_DATE(param);
        JSONArray result = new JSONArray();
        array.forEach(data -> {
            JSONObject resultData = new JSONObject();
            JSONObject object = (JSONObject) data;
            if (param.get("COMPANYID") != null) {
                resultData.put("COMPANY_ID", object.get("COMPANY_ID"));
                resultData.put("COMPANY_NAME", object.get("COMPANY_NAME"));
            } else {
                resultData.put("COMPANY_NAME", "赋能公司");
            }
            if (param.get("DEPTID") != null) {
                resultData.put("DEPT_ID", object.get("DEPT_ID"));
                resultData.put("DEPT_NAME", object.get("DEPT_NAME"));
            }
            param.put("typeDate", "day");
            result.add(matchResult(object, resultData, param));
        });
        if (param.get("DEPTID") != null) {
            objDate.put("DAILYlIST", result);
        } else {
            JSONArray resultStatistics = new JSONArray();
            Map<Date, List<Object>> map = array.stream().collect(Collectors.groupingBy(x -> ((JSONObject) x).getDate("DATE_OF_STATISTICS")));
            map.forEach((k, v) -> {

                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("DATE_OF_STATISTICS", k.getTime());
                    resultStatistics.add(matchResultStatistics(JSONArray.parseArray(JSON.toJSONString(v)), jsonObject, this::processDataStatistics));
                } catch (Exception e) {
                    e.printStackTrace();
                }

            });
            objDate.put("DAILYlIST", resultStatistics);
        }


        return objDate;
    }


    /***
     * 查询销售月数据
     */
    public JSONObject findRCL_MonthSALESREPORT(SimpleRequest request) throws Exception {
        JSONObject param = request.getJO();

        JSONObject objDate = new JSONObject();

        if (param.get("DEPTID") != null) {
            param.put("COMPANYID", deptListGetCompanyIds(param));
        }
        findLastMonthDate(param);
        param.put("merge", "1");
        //获取查询数据
        JSONArray array = reportDaliyDao.findRCL_MOnthSALESREPORT(param);
        JSONArray result = new JSONArray();
        array.forEach(data -> {
            JSONObject resultData = new JSONObject();
            JSONObject object = (JSONObject) data;
            if (param.get("COMPANYID") != null) {
                resultData.put("COMPANY_ID", object.get("COMPANY_ID"));
                resultData.put("COMPANY_NAME", object.get("COMPANY_NAME"));
            } else {
                resultData.put("COMPANY_NAME", "赋能公司");
            }
            if (param.get("DEPTID") != null) {
                resultData.put("DEPT_ID", object.get("DEPT_ID"));
                resultData.put("DEPT_NAME", object.get("DEPT_NAME"));
            }
            param.put("typeDate", "month");
            result.add(matchResult(object, resultData, param));
        });
        if (param.get("DEPTID") != null) {
            objDate.put("MonthList", result);
        } else {
            JSONArray resultStatistics = new JSONArray();
            resultStatistics.add(matchResultStatistics(array, new JSONObject(), this::processDataStatisticsMonth));
            objDate.put("MonthList", resultStatistics);
        }

        return objDate;
    }

    private void findLastMonthDate(JSONObject param) {

        if (param.containsKey("LAST_MONTH_LAST")) {
            param.put("LAST_MONTH_FIRST", param.getDate("LAST_MONTH_FIRST"));
            param.put("LAST_MONTH_LAST", param.getDate("LAST_MONTH_LAST"));

            return;
        }
        //获取上月第一天和上月最后一天
        SimpleDateFormat dtf = new SimpleDateFormat("yyyyMM");
        String YEAR_AND_MONTH = param.getString("YEAR_AND_MONTH");
        //上月第一天
        try {
            Date parse = DateUtil.add(dtf.parse(YEAR_AND_MONTH), Calendar.MONTH, -1);
            param.put("LAST_MONTH_FIRST", parse);
            //当查询的是当前月份的话 上月日期最后一天取当前时间-1月
            if (dtf.format(new Date()).equals(YEAR_AND_MONTH)) {
                param.put("LAST_MONTH_LAST", DateUtil.add(new Date(), Calendar.MONTH, -1));
            } else {
                param.put("LAST_MONTH_LAST", DateUtil.getMonthLastDay(parse));
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取门店营业额
     *
     * @param request
     * @return
     */
    public JSONObject findStoreTurnover(SimpleRequest request) {
        JSONObject param = request.getJO();

        JSONObject result = new JSONObject();
        result.put("DAY_SALE_MONEY", 0);
        result.put("DAY_TIMES_OF_ENTERING_THE_STORE", 0);
        result.put("MONTH_SALE_MONEY", 0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.format(new Date());
        if (StringUtil.isEmpty(param.getString("DEPTID"))) {
            throw new RuntimeException("门店编码必填");
        }
        try {
            param.put("STARTDATE", sdf.parse(sdf.format(new Date())));
            param.put("ENDDATE", sdf.parse(sdf.format(new Date())));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (!StringUtil.isEmpty(param.getString("DEPTID"))) {
            Dept dept = deptRepository.findOne(param.getString("DEPTID"));
            param.put("COMPANYID", dept.getCompany().getId());
        }

        //获取查询数据
        JSONArray array_day = reportDaliyDao.findRCL_DAILYSALESREPORT_ALL(param);
        array_day.stream().findFirst().ifPresent(x -> {
            result.put("DAY_SALE_MONEY", ((Map<? extends String, ? extends Object>) x).get("SALE_MONEY"));
            result.put("DAY_TIMES_OF_ENTERING_THE_STORE", ((Map<? extends String, ? extends Object>) x).get("TIMES_OF_ENTERING_THE_STORE"));
        });
        //获取查询数据
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
        param.put("YEAR_AND_MONTH", simpleDateFormat.format(new Date()));
        String YEAR_AND_MONTH = simpleDateFormat.format(new Date());
        //上月第一天
        try {
            Date parse = DateUtil.add(simpleDateFormat.parse(YEAR_AND_MONTH), Calendar.MONTH, -1);
            param.put("LAST_MONTH_FIRST", parse);
            //当查询的是当前月份的话 上月日期最后一天取当前时间-1月
            if (simpleDateFormat.format(new Date()).equals(YEAR_AND_MONTH)) {
                param.put("LAST_MONTH_LAST", DateUtil.add(new Date(), Calendar.MONTH, -1));
            } else {
                param.put("LAST_MONTH_LAST", DateUtil.getMonthLastDay(parse));
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        param.put("YEARCARD_LESS", "1");
        JSONArray array = reportDaliyDao.findRCL_MOnthSALESREPORT(param);
        array.stream().findFirst().ifPresent(x -> result.put("MONTH_SALE_MONEY", ((Map<? extends String, ? extends Object>) x).get("SALE_MONEY")));
        return result;
    }

    /***
     * 查询销售日数据排名
     */
    public JSONObject getDayRank(SimpleRequest request) throws Exception {
        JSONObject param = request.getJO();

        JSONObject objDate = new JSONObject();

        Date strarD = param.getDate("DATE_OF_STATISTICSs");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String sStartDate = sdf.format(strarD);

        Date startDate = sdf.parse(sStartDate);

        param.put("DATE_OF_STATISTICS", startDate);

        if (param.get("DEPTID") != null) {
            param.put("COMPANY_ID", deptListGetCompanyIds(param));
        }


        //获取查询数据
        JSONArray array = reportDaliyDao.getDayRank(param);
        objDate.put("rankList", array);

        return objDate;
    }

    /***
     * 查询销售 时间区间数据排名
     */
    public JSONObject getWeekRank(SimpleRequest request) throws Exception {
        JSONObject param = request.getJO();

        JSONObject objDate = new JSONObject();

        Date strarD = param.getDate("STARTDATE");
        Date strarE = param.getDate("ENDDATE");
        long eTime = strarE.getTime();
        long strarDTime = strarD.getTime();
        long l = eTime - strarDTime;

        param.put("STARTDATE", strarD);
        param.put("ENDDATE", strarE);
        strarD.setTime(strarDTime - l);
        strarE.setTime(eTime - l);
        param.put("LAST_START_DATE", strarD);
        param.put("LAST_END_DATE", strarE);

        if (param.get("DEPTID") != null) {
            param.put("COMPANY_ID", deptListGetCompanyIds(param));
        }

        //获取查询数据
        JSONArray array = reportDaliyDao.getWeekRank(param);
        objDate.put("rankList", array);

        return objDate;
    }


    /**
     * 查询月度排名报表
     *
     * @param request
     * @return
     * @throws Exception
     */
    public JSONObject getMonthRank(SimpleRequest request) throws Exception {
        JSONObject param = request.getJO();

        JSONObject objDate = new JSONObject();
        if (param.get("DEPTID") != null) {
            param.put("COMPANY_ID", deptListGetCompanyIds(param));
        }

        //获取查询数据
        JSONArray array = reportDaliyDao.getMonthRank(param);
        objDate.put("rankList", array);

        return objDate;
    }


    /**
     * 匹配返回结果
     *
     * @param data
     * @param result
     * @param consumer
     * @return
     */
    public JSONObject matchResult(JSONObject data, JSONObject result, BiConsumer<JSONObject, JSONObject> consumer) {
        result.put("ACCOUNTS_RECEIVABLEIN", data.get("ACCOUNTS_RECEIVABLEIN"));
        result.put("ACCOUNTS_RECEIVABLEOUT", data.get("ACCOUNTS_RECEIVABLEOUT"));
        result.put("ADVANCE_PAYMENT", data.get("ADVANCE_PAYMENT"));
        result.put("BUY_YEARCARD", data.get("BUY_YEARCARD"));
        result.put("YEARCARD", data.get("YEARCARD"));
        result.put("STORED_VALUE_AMOUNT", data.get("STORED_VALUE_AMOUNT"));
        result.put("ADVANCE_PAYMENT_RECHARGE", data.get("ADVANCE_PAYMENT_RECHARGE"));
        result.put("ADVANCE_AMOUNT", data.get("ADVANCE_AMOUNT"));
        result.put("CAPITAL_INCOME", data.get("CAPITAL_INCOME"));
        result.put("DATE_OF_STATISTICS", data.get("DATE_OF_STATISTICS"));
        result.put("FIXED_LOSS", data.get("FIXED_LOSS"));
        result.put("FIXED_LOSS_COLLECTION", data.get("FIXED_LOSS_COLLECTION"));
        result.put("FIXED_LOSS_DIRECT_COMPENSATION", data.get("FIXED_LOSS_DIRECT_COMPENSATION"));
        result.put("FLUSH_DATE", data.get("FLUSH_DATE"));
        result.put("CROSS_COMPANY_INCOME", data.get("CROSS_COMPANY_INCOME"));
        result.put("CROSS_COMPANY_PAY", data.get("CROSS_COMPANY_PAY"));
        result.put("STORED_VALUE", data.get("STORED_VALUE"));
        result.put("STORED_VALUE_RECHARGE", data.get("STORED_VALUE_RECHARGE"));
        result.put("STORED_VALUE_RETAIL", data.get("STORED_VALUE_RETAIL"));
        result.put("TIMES_OF_ENTERING_THE_STORE", data.get("TIMES_OF_ENTERING_THE_STORE"));
        result.put("INSURANCE_ORDER_AMT", data.get("INSURANCE_ORDER_AMT"));
        result.put("SALE_MONEY", data.get("SALE_MONEY"));
        result.put("USER_CAR_FEE", data.get("USER_CAR_FEE"));
        result.put("SERVICE_PERFORMANCE", data.get("SERVICE_PERFORMANCE"));
        result.put("FN_COMMISSION", data.get("FN_COMMISSION"));
        result.put("FN_SETTLE_EXPENS", data.get("FN_SETTLE_EXPENS"));
        result.put("USERD_CAR_FINAL", data.get("USERD_CAR_FINAL"));
        result.put("INSURANCE_AMOUNT", data.get("INSURANCE_AMOUNT"));
        result.put("OUR_LOSS_COLLECTION", data.get("OUR_LOSS_COLLECTION"));
        result.put("INNER_LOSS_COLLECTION", data.get("INNER_LOSS_COLLECTION"));
        result.put("SELF_FIXED_LOSS", data.get("SELF_FIXED_LOSS"));
        //保险业绩环比
        result.put("INSURANCE_ORDER_AMT_MONTHONMONTH", data.get("INSURANCE_MONTHONMONTH"));
        //服务环比
        result.put("SERVICE_PERFORMANCE_MONTHONMONTH", data.get("SERVICE_MONTHONMONTH_LESS"));
        //年卡环比
        result.put("BUY_YEARCARD_MONTHONMONTH", data.get("BUY_YEARCARD_MONTHONMONTH"));
        //定损环比
        result.put("FIXED_LOSS_MONTHONMONTH", data.get("FIXED_LOSS_MONTHONMONTH"));
        //车流环比
        result.put("TIMES_MONTHONMONTH", data.get("TIMES_MONTHONMONTH"));
        //二手车服务费环比
        result.put("USER_CAR_FEE_MONTHONMONTH", data.get("USER_CAR_FEE_MONTHONMONTH"));
        //车险佣金环比
        result.put("FN_COMMISSION_MONTHONMONTH", data.get("FN_COMMISSION_MONTHONMONTH"));
        //车险佣金环比
        result.put("INSURANCE_AMOUNT_MONTHONMONTH", data.get("INSURANCE_AMOUNT_MONTHONMONTH"));
        //本地定损
        result.put("OUR_LOSS_MONTHONMONTH", data.get("OUR_LOSS_MONTHONMONTH"));
        //接案介绍费环比
        result.put("FN_SETTLE_EXPENS_MONTHONMONTH", data.get("FN_SETTLE_EXPENS_MONTHONMONTH"));
        //二手车交易环比
        result.put("USERD_CAR_FINAL_MONTHONMONTH", data.get("USERD_CAR_FINAL_MONTHONMONTH"));
        //销售金额环比
        result.put("SALE_MONEY_MONTHONMONTH", data.get("SALE_MONEY_MONTHONMONTH"));
        consumer.accept(result, data);
        return result;
    }

    /**
     * 匹配返回结果
     *
     * @param data
     * @param result
     * @param param
     * @return
     */
    public JSONObject matchResult(JSONObject data, JSONObject result, JSONObject param) {
        result.put("ACCOUNTS_RECEIVABLEIN", data.get("ACCOUNTS_RECEIVABLEIN"));
        result.put("ACCOUNTS_RECEIVABLEOUT", data.get("ACCOUNTS_RECEIVABLEOUT"));
        result.put("ADVANCE_PAYMENT", data.get("ADVANCE_PAYMENT"));
        result.put("BUY_YEARCARD", data.get("BUY_YEARCARD"));
        result.put("YEARCARD", data.get("YEARCARD"));
        result.put("STORED_VALUE_AMOUNT", data.get("STORED_VALUE_AMOUNT"));
        result.put("ADVANCE_PAYMENT_RECHARGE", data.get("ADVANCE_PAYMENT_RECHARGE"));
        result.put("ADVANCE_AMOUNT", data.get("ADVANCE_AMOUNT"));
        result.put("CAPITAL_INCOME", data.get("CAPITAL_INCOME"));
        result.put("DATE_OF_STATISTICS", data.get("DATE_OF_STATISTICS"));
        result.put("FIXED_LOSS", data.get("FIXED_LOSS"));
        result.put("FIXED_LOSS_COLLECTION", data.get("FIXED_LOSS_COLLECTION"));
        result.put("FIXED_LOSS_DIRECT_COMPENSATION", data.get("FIXED_LOSS_DIRECT_COMPENSATION"));
        result.put("FLUSH_DATE", data.get("FLUSH_DATE"));
        result.put("CROSS_COMPANY_INCOME", data.get("CROSS_COMPANY_INCOME"));
        result.put("CROSS_COMPANY_PAY", data.get("CROSS_COMPANY_PAY"));
        result.put("STORED_VALUE", data.get("STORED_VALUE"));
        result.put("STORED_VALUE_RECHARGE", data.get("STORED_VALUE_RECHARGE"));
        result.put("STORED_VALUE_RETAIL", data.get("STORED_VALUE_RETAIL"));
        result.put("TIMES_OF_ENTERING_THE_STORE", data.get("TIMES_OF_ENTERING_THE_STORE"));
        result.put("INSURANCE_ORDER_AMT", data.get("INSURANCE_ORDER_AMT"));
        result.put("SALE_MONEY", data.get("SALE_MONEY"));
        result.put("USER_CAR_FEE", data.get("USER_CAR_FEE"));
        result.put("SERVICE_PERFORMANCE", data.get("SERVICE_PERFORMANCE"));
        result.put("FN_COMMISSION", data.get("FN_COMMISSION"));
        result.put("FN_SETTLE_EXPENS", data.get("FN_SETTLE_EXPENS"));
        result.put("USERD_CAR_FINAL", data.get("USERD_CAR_FINAL"));
        result.put("INSURANCE_AMOUNT", data.get("INSURANCE_AMOUNT"));
        result.put("OUR_LOSS_COLLECTION", data.get("OUR_LOSS_COLLECTION"));
        result.put("INNER_LOSS_COLLECTION", data.get("INNER_LOSS_COLLECTION"));
        result.put("SELF_FIXED_LOSS", data.get("SELF_FIXED_LOSS"));
        //保险业绩环比
        result.put("INSURANCE_ORDER_AMT_MONTHONMONTH", data.get("INSURANCE_MONTHONMONTH"));
        //服务环比
        result.put("SERVICE_PERFORMANCE_MONTHONMONTH", data.get("SERVICE_MONTHONMONTH_LESS"));
        //年卡环比
        result.put("BUY_YEARCARD_MONTHONMONTH", data.get("BUY_YEARCARD_MONTHONMONTH"));
        //定损环比
        result.put("FIXED_LOSS_MONTHONMONTH", data.get("FIXED_LOSS_MONTHONMONTH"));
        //车流环比
        result.put("TIMES_MONTHONMONTH", data.get("TIMES_MONTHONMONTH"));
        //二手车服务费环比
        result.put("USER_CAR_FEE_MONTHONMONTH", data.get("USER_CAR_FEE_MONTHONMONTH"));
        //车险佣金环比
        result.put("FN_COMMISSION_MONTHONMONTH", data.get("FN_COMMISSION_MONTHONMONTH"));
        //车险佣金环比
        result.put("INSURANCE_AMOUNT_MONTHONMONTH", data.get("INSURANCE_AMOUNT_MONTHONMONTH"));
        //本地定损
        result.put("OUR_LOSS_MONTHONMONTH", data.get("OUR_LOSS_MONTHONMONTH"));
        //接案介绍费环比
        result.put("FN_SETTLE_EXPENS_MONTHONMONTH", data.get("FN_SETTLE_EXPENS_MONTHONMONTH"));
        //二手车交易环比
        result.put("USERD_CAR_FINAL_MONTHONMONTH", data.get("USERD_CAR_FINAL_MONTHONMONTH"));
        //销售金额环比
        result.put("SALE_MONEY_MONTHONMONTH", data.get("SALE_MONEY_MONTHONMONTH"));
        if ("day".equals(param.getString("typeDate"))) processDataDayInset(result, data, param);
        if ("month".equals(param.getString("typeDate"))) processDataMonth(result, data, param);
        return result;
    }

    /**
     * 匹配返回结果(统计)
     *
     * @param data
     * @param result
     * @param consumer
     * @return
     */
    public JSONObject matchResultStatistics(JSONArray data, JSONObject result, BiConsumer<JSONObject, JSONArray> consumer) {
        result.put("ACCOUNTS_RECEIVABLEIN", calculationSum(data.stream(), "ACCOUNTS_RECEIVABLEIN"));
        result.put("BUY_YEARCARD", calculationSum(data.stream(), "BUY_YEARCARD"));
        result.put("YEARCARD", calculationSum(data.stream(), "YEARCARD"));
        result.put("ACCOUNTS_RECEIVABLEOUT", calculationSum(data.stream(), "ACCOUNTS_RECEIVABLEOUT"));
        result.put("ADVANCE_PAYMENT", calculationSum(data.stream(), "ADVANCE_PAYMENT"));
        result.put("ADVANCE_PAYMENT_RECHARGE", calculationSum(data.stream(), "ADVANCE_PAYMENT_RECHARGE"));
        result.put("CAPITAL_INCOME", calculationSum(data.stream(), "CAPITAL_INCOME"));
        result.put("FIXED_LOSS", calculationSum(data.stream(), "FIXED_LOSS"));
        result.put("FIXED_LOSS_COLLECTION", calculationSum(data.stream(), "FIXED_LOSS_COLLECTION"));
        result.put("FIXED_LOSS_DIRECT_COMPENSATION", calculationSum(data.stream(), "FIXED_LOSS_DIRECT_COMPENSATION"));
        result.put("FLUSH_DATE", data.size() == 0 ? "" : data.getJSONObject(0).get("FLUSH_DATE"));
        result.put("STORED_VALUE", calculationSum(data.stream(), "STORED_VALUE"));
        result.put("STORED_VALUE_RECHARGE", calculationSum(data.stream(), "STORED_VALUE_RECHARGE"));
        result.put("STORED_VALUE_AMOUNT", calculationSum(data.stream(), "STORED_VALUE_AMOUNT"));
        result.put("ADVANCE_AMOUNT", calculationSum(data.stream(), "ADVANCE_AMOUNT"));
        result.put("STORED_VALUE_RETAIL", calculationSum(data.stream(), "STORED_VALUE_RETAIL"));
        result.put("TIMES_OF_ENTERING_THE_STORE", calculationSum(data.stream(), "TIMES_OF_ENTERING_THE_STORE"));
        result.put("INSURANCE_ORDER_AMT", calculationSum(data.stream(), "INSURANCE_ORDER_AMT"));
        result.put("SALE_MONEY", calculationSum(data.stream(), "SALE_MONEY"));
        result.put("SERVICE_PERFORMANCE", calculationSum(data.stream(), "SERVICE_PERFORMANCE"));
        result.put("CROSS_COMPANY_INCOME", calculationSum(data.stream(), "CROSS_COMPANY_INCOME"));
        result.put("CROSS_COMPANY_PAY", calculationSum(data.stream(), "CROSS_COMPANY_PAY"));
        result.put("USER_CAR_FEE", calculationSum(data.stream(), "USER_CAR_FEE"));
        result.put("FN_COMMISSION", calculationSum(data.stream(), "FN_COMMISSION"));
        result.put("FN_SETTLE_EXPENS", calculationSum(data.stream(), "FN_SETTLE_EXPENS"));
        result.put("USERD_CAR_FINAL", calculationSum(data.stream(), "USERD_CAR_FINAL"));
        result.put("INSURANCE_AMOUNT", calculationSum(data.stream(), "INSURANCE_AMOUNT"));
        result.put("OUR_LOSS_COLLECTION", calculationSum(data.stream(), "OUR_LOSS_COLLECTION"));
        result.put("INNER_LOSS_COLLECTION", calculationSum(data.stream(), "INNER_LOSS_COLLECTION"));
        result.put("SELF_FIXED_LOSS", calculationSum(data.stream(), "SELF_FIXED_LOSS"));
        result.put("DEPT_NAME", "赋能门店");
        JSONObject calculationResult = calculationEntry(data, "INSURANCE_ORDER_AMT", null, 0.0, data.stream().mapToDouble((m) -> ((JSONObject) m).getDoubleValue("INSURANCE_ORDER_AMT_LASTMONTH")).sum());
        //保险业绩环比
        result.put("INSURANCE_ORDER_AMT_MONTHONMONTH", calculationResult.get("month"));
        //服务环比
        calculationResult = calculationEntry(data, "SERVICE_PERFORMANCE", null, 0.0, data.stream().mapToDouble((m) -> ((JSONObject) m).getDoubleValue("SERVICE_LASTMONTH_LESS")).sum());
        result.put("SERVICE_PERFORMANCE_MONTHONMONTH", calculationResult.get("month"));
        //年卡环比
        calculationResult = calculationEntry(data, "BUY_YEARCARD", null, 0.0, data.stream().mapToDouble((m) -> ((JSONObject) m).getDoubleValue("BUY_YEARCARD_LASTMONTH")).sum());
        result.put("BUY_YEARCARD_MONTHONMONTH", calculationResult.get("month"));
        //定损环比
        calculationResult = calculationEntry(data, "FIXED_LOSS_ALL", null, 0.0, data.stream().mapToDouble((m) -> ((JSONObject) m).getDoubleValue("FIXED_LOSS_LASTMONTH")).sum());
        result.put("FIXED_LOSS_MONTHONMONTH", calculationResult.get("month"));
        //车流环比
        calculationResult = calculationEntry(data, "TIMES_OF_ENTERING_THE_STORE", null, 0.0, data.stream().mapToDouble((m) -> ((JSONObject) m).getDoubleValue("TIMES_LASTMONTH")).sum());
        result.put("TIMES_MONTHONMONTH", calculationResult.get("month"));
        //二手车服务费环比
        calculationResult = calculationEntry(data, "USER_CAR_FEE", null, 0.0, data.stream().mapToDouble((m) -> ((JSONObject) m).getDoubleValue("USER_CAR_FEE_LASTMONTH")).sum());
        result.put("USER_CAR_FEE_MONTHONMONTH", calculationResult.get("month"));
        //车险佣金环比
        calculationResult = calculationEntry(data, "FN_COMMISSION", null, 0.0, data.stream().mapToDouble((m) -> ((JSONObject) m).getDoubleValue("FN_COMMISSION_LASTMONTH")).sum());
        result.put("FN_COMMISSION_MONTHONMONTH", calculationResult.get("month"));
        //车险销售环比
        calculationResult = calculationEntry(data, "INSURANCE_AMOUNT", null, 0.0, data.stream().mapToDouble((m) -> ((JSONObject) m).getDoubleValue("INSURANCE_AMOUNT_LASTMONTH")).sum());
        result.put("INSURANCE_AMOUNT_MONTHONMONTH", calculationResult.get("month"));
        //本店定损环比
        calculationResult = calculationEntry(data, "OUR_LOSS_COLLECTION", null, 0.0, data.stream().mapToDouble((m) -> ((JSONObject) m).getDoubleValue("OUR_LOSS_COLLECTION_LASTMONTH")).sum());
        result.put("OUR_LOSS_MONTHONMONTH", calculationResult.get("month"));
        //接案介绍费环比
        calculationResult = calculationEntry(data, "FN_SETTLE_EXPENS", null, 0.0, data.stream().mapToDouble((m) -> ((JSONObject) m).getDoubleValue("FN_SETTLE_EXPENS_LASTMONTH")).sum());
        result.put("FN_SETTLE_EXPENS_MONTHONMONTH", calculationResult.get("month"));
        //二手车交易环比
        calculationResult = calculationEntry(data, "USERD_CAR_FINAL", null, 0.0, data.stream().mapToDouble((m) -> ((JSONObject) m).getDoubleValue("USERD_CAR_FINAL_LASTMONTH")).sum());
        result.put("USERD_CAR_FINAL_MONTHONMONTH", calculationResult.get("month"));
        //销售金额环比
        calculationResult = calculationEntry(data, "SALE_MONEY", null, 0.0, data.stream().mapToDouble((m) -> ((JSONObject) m).getDoubleValue("SALE_MONEY_LASTMONTH")).sum());
        result.put("SALE_MONEY_MONTHONMONTH", calculationResult.get("month"));
        consumer.accept(result, data);
        return result;
    }

    /**
     * 数据处理(统计 日)
     *
     * @param result
     * @param data
     * @return
     */
    public JSONObject processDataStatistics(JSONObject result, JSONArray data) {
        JSONArray category = new JSONArray();
        Double service_performance = result.getDouble("SERVICE_PERFORMANCE") + result.getDouble("YEARCARD");
        //洗车
        JSONObject calculationResult = calculationEntry(data, "CAR_WASH", "CAR_WASH_TIMES", service_performance, 0.0);
        category.add(mapper("NAME", "洗车", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{}));
        //美容
        calculationResult = calculationEntry(data, "COSMETOLOGY", "COSMETOLOGY_TIMES", service_performance, 0.0);
        category.add(mapper("NAME", "美容", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{}));
        //保养
        calculationResult = calculationEntry(data, "MAINTAIN", "MAINTAIN_TIMES", service_performance, 0.0);
        category.add(mapper("NAME", "保养", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{}));
        //维修
        calculationResult = calculationEntry(data, "REPAIR", "REPAIR_TIMES", service_performance, 0.0);
        category.add(mapper("NAME", "维修", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{}));
        //钣喷
        calculationResult = calculationEntry(data, "SHEET_METAL_SPRAY", "SHEET_METAL_SPRAY_TIMES", service_performance, 0.0);
        category.add(mapper("NAME", "钣喷", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{}));
        //改装
        calculationResult = calculationEntry(data, "REFIT", "REFIT_TIMES", service_performance, 0.0);
        category.add(mapper("NAME", "改装", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{}));
        //年卡
//        category.add(mapper("NAME", "年卡", "YEARCARD", data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("YEARCARD")).sum(), "BUY_YEARCARD", data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("BUY_YEARCARD")).sum(), "ITEM", new Object[]{}));
        //轮胎
        calculationResult = calculationEntry(data, "TYRE", "TYRE_TIMES", service_performance, 0.0);
        category.add(mapper("NAME", "轮胎", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{}));
        //精品
        calculationResult = calculationEntry(data, "BOUTIQUE", null, service_performance, 0.0);
        category.add(mapper("NAME", "精品", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", 0, "ITEM", new Object[]{}));
        //生活用品
        calculationResult = calculationEntry(data, "ARTICLES_FOR_DAILY_USE", null, service_performance, 0.0);
        category.add(mapper("NAME", "生活用品", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", 0, "ITEM", new Object[]{}));
        //道路救援
        calculationResult = calculationEntry(data, "ROAD_RESCUE", "ROAD_RESCUE_TIMES", service_performance, 0.0);
        category.add(mapper("NAME", "道路救援金额", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{}));
        //信息服务
        calculationResult = calculationEntry(data, "INFORMATION_SERVICE", null, service_performance, 0.0);
        category.add(mapper("NAME", "信息服务", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", 0, "ITEM", new Object[]{}));
        //技术检测
        calculationResult = calculationEntry(data, "TECHNICAL_INSPECTION", null, service_performance, 0.0);
        category.add(mapper("NAME", "技术检测", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", 0, "ITEM", new Object[]{}));
        result.put("CATEGORY", category);
        return result;
    }

    /**
     * 数据处理(统计 月)
     *
     * @param result
     * @param data
     * @return
     */
    public JSONObject processDataStatisticsMonth(JSONObject result, JSONArray data) {
        JSONArray category = new JSONArray();
        Double service_performance = result.getDouble("SERVICE_PERFORMANCE") + result.getDouble("YEARCARD");
        //洗车
        JSONObject calculationResult = calculationEntry(data, "CAR_WASH", "CAR_WASH_TIMES", service_performance, data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("CAR_WASH_LASTMONTH")).sum());
        category.add(mapper("NAME", "洗车", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", calculationResult.get("month") + "%")}));
        //美容
        calculationResult = calculationEntry(data, "COSMETOLOGY", "COSMETOLOGY_TIMES", service_performance, data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("COSMETOLOGY_LASTMONTH")).sum());
        category.add(mapper("NAME", "美容", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", calculationResult.get("month") + "%")}));
        //保养
        calculationResult = calculationEntry(data, "MAINTAIN", "MAINTAIN_TIMES", service_performance, data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("MAINTAIN_LASTMONTH")).sum());
        category.add(mapper("NAME", "保养", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", calculationResult.get("month") + "%")}));
        //维修
        calculationResult = calculationEntry(data, "REPAIR", "REPAIR_TIMES", service_performance, data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("REPAIR_LASTMONTH")).sum());
        category.add(mapper("NAME", "维修", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", calculationResult.get("month") + "%")}));
        //钣喷
        calculationResult = calculationEntry(data, "SHEET_METAL_SPRAY", "SHEET_METAL_SPRAY_TIMES", service_performance, data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("SHEET_METAL_SPRAY_LASTMONTH")).sum());
        category.add(mapper("NAME", "钣喷", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", calculationResult.get("month") + "%")}));
        //改装
        calculationResult = calculationEntry(data, "REFIT", "REFIT_TIMES", service_performance, data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("REFIT_LASTMONTH")).sum());
        category.add(mapper("NAME", "改装", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", calculationResult.get("month") + "%")}));
        //年卡
//        category.add(mapper("NAME", "年卡", "YEARCARD", data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("YEARCARD")).sum(), "BUY_YEARCARD", data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("BUY_YEARCARD")).sum(), "ITEM", new Object[]{}));
        //轮胎
        calculationResult = calculationEntry(data, "TYRE", "TYRE_TIMES", service_performance, data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("TYRE_LASTMONTH")).sum());
        category.add(mapper("NAME", "轮胎", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", calculationResult.get("month") + "%")}));
        //精品
        calculationResult = calculationEntry(data, "BOUTIQUE", null, service_performance, data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("BOUTIQUE_LASTMONTH")).sum());
        category.add(mapper("NAME", "精品", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", 0, "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", calculationResult.get("month") + "%")}));
        //生活用品
        calculationResult = calculationEntry(data, "ARTICLES_FOR_DAILY_USE", null, service_performance, data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("ARTICLES_FOR_LASTMONTH")).sum());
        category.add(mapper("NAME", "生活用品", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", 0, "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", calculationResult.get("month") + "%")}));
        //道路救援
        calculationResult = calculationEntry(data, "ROAD_RESCUE", "ROAD_RESCUE_TIMES", service_performance, data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("ROAD_RESCUE_LASTMONTH")).sum());
        category.add(mapper("NAME", "道路救援金额", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", calculationResult.get("month") + "%")}));
        //信息服务
        calculationResult = calculationEntry(data, "INFORMATION_SERVICE", null, service_performance, data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("INFORMATION_SERVICE_LASTMONTH")).sum());
        category.add(mapper("NAME", "信息服务", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", 0, "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", calculationResult.get("month") + "%")}));
        //技术检测
        calculationResult = calculationEntry(data, "TECHNICAL_INSPECTION", null, service_performance, data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("TECHNICAL_INSPECTION_LASTMONTH")).sum());
        category.add(mapper("NAME", "技术检测", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", 0, "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", calculationResult.get("month") + "%")}));
        //定损
//        calculationResult = calculationEntry(data, "OUR_LOSS_COLLECTION", null, service_performance, data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble("CAR_WASH_LASTMONTH")).sum());
//        category.add(mapper("NAME", "洗车", "AMOUNT", calculationResult.get("sum"), "RATE", calculationResult.get("rate"), "TIMES", calculationResult.get("times"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", calculationResult.get("month") + "%")}));
        result.put("CATEGORY", category);
        return result;
    }

    /**
     * 统计计算入口
     *
     * @param data
     * @param amount
     * @param time
     * @param service_performance
     * @return
     */
    public JSONObject calculationEntry(JSONArray data, String amount, String time, Double service_performance, Double last) {
        JSONObject result = new JSONObject();
        double sum = data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble(amount)).sum();
        if (time != null) {
            double times = data.stream().mapToDouble((m) -> ((JSONObject) m).getDouble(time)).sum();
            result.put("times", times > 0 ? times : 0);
        }
        result.put("sum", sum != 0 ? Arith.round(sum, 2) : 0);
        double rate = service_performance == 0 ? 0 : (sum / service_performance * 100);
        result.put("rate", rate > 0 ? Arith.round(rate, 2) : 0);
        if (last != 0) {
            result.put("month", Arith.round(((sum - last) / last) * 100, 2));
        } else {
            result.put("month", 0);

        }
        return result;
    }

    /**
     * 计算总计
     *
     * @param stream
     * @param value
     * @return
     */
    private String calculationSum(Stream stream, String value) {
        double sum = stream.mapToDouble((m) -> ((JSONObject) m).getDouble(value)).sum();
        return sum != 0 ? formatFloatNumber(Arith.round(sum, 2)) : "0";
    }

    /**
     * 当浮点型数据位数超过10位之后，数据变成科学计数法显示。用此方法可以使其正常显示
     *
     * @param value
     * @return
     */
    public static String formatFloatNumber(double value) {
        if (value != 0.00) {
            DecimalFormat df = new DecimalFormat("########.00");
            return df.format(value);
        } else {
            return "0.00";
        }

    }

    /**
     * 数据处理(月)
     *
     * @param result
     * @param data
     * @return
     */
    public JSONObject processDataMonth(JSONObject result, JSONObject data) {
        JSONArray category = new JSONArray();
        //洗车
        category.add(mapper("NAME", "洗车", "AMOUNT", data.get("CAR_WASH"), "RATE", data.get("CAR_WASH_RATE"), "TIMES", data.get("CAR_WASH_TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("CAR_WASH_MONTHONMONTH") + "%")}));
        //美容
        category.add(mapper("NAME", "美容", "AMOUNT", data.get("COSMETOLOGY"), "RATE", data.get("COSMETOLOGY_RATE"), "TIMES", data.get("COSMETOLOGY_TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("COSMETOLOGY_MONTHONMONTH") + "%")}));
        //保养
        category.add(mapper("NAME", "保养", "AMOUNT", data.get("MAINTAIN"), "RATE", data.get("MAINTAIN_RATE"), "TIMES", data.get("MAINTAIN_TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("MAINTAIN_MONTHONMONTH") + "%")}));
        //维修
        category.add(mapper("NAME", "维修", "AMOUNT", data.get("REPAIR"), "RATE", data.get("REPAIR_RATE"), "TIMES", data.get("REPAIR_TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("REPAIR_MONTHONMONTH") + "%")}));
        //钣喷
        category.add(mapper("NAME", "钣喷", "AMOUNT", data.get("SHEET_METAL_SPRAY"), "RATE", data.get("SHEET_METAL_SPRAY_RATE"), "TIMES", data.get("SHEET_METAL_SPRAY_TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("SHEET_METAL_SPRAY_MONTHONMONTH") + "%")}));
        //改装
        category.add(mapper("NAME", "改装", "AMOUNT", data.get("REFIT"), "RATE", data.get("REFIT_RATE"), "TIMES", 0, "ITEM", new Object[]{mapper("LABEL", "台次", "VALUE", data.get("REFIT_TIMES")), mapper("LABEL", "环比", "VALUE", data.get("REFIT_MONTHONMONTH") + "%")}));
        //年卡
//        category.add(mapper("NAME", "年卡", "YEARCARD", data.get("YEARCARD"), "BUY_YEARCARD", data.get("BUY_YEARCARD"), "ITEM", new Object[]{}));
        //轮胎
        category.add(mapper("NAME", "轮胎", "AMOUNT", data.get("TYRE"), "RATE", data.get("TYRE_RATE"), "TIMES", data.get("TYRE_TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("TYRE_MONTHONMONTH") + "%")}));
        //精品
        category.add(mapper("NAME", "精品", "AMOUNT", data.get("BOUTIQUE"), "RATE", data.get("BOUTIQUE_RATE"), "TIMES", 0, "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("BOUTIQUE_MONTHONMONTH") + "%")}));
        //生活用品
        category.add(mapper("NAME", "生活用品", "AMOUNT", data.get("ARTICLES_FOR_DAILY_USE"), "RATE", data.get("ARTICLES_FOR_DAILY_USE_RATE"), "TIMES", 0, "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("ARTICLES_MONTHONMONTH") + "%")}));
        //道路救援
        category.add(mapper("NAME", "道路救援金额", "AMOUNT", data.get("ROAD_RESCUE"), "RATE", data.get("ROAD_RESCUE_RATE"), "TIMES", data.get("ROAD_RESCUE_TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("ROAD_RESCUE_MONTHONMONTH") + "%")}));
        //信息服务
        category.add(mapper("NAME", "信息服务", "AMOUNT", data.get("INFORMATION_SERVICE"), "RATE", data.get("INFORMATION_SERVICE_RATE"), "TIMES", 0, "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("INFORMATION_MONTHONMONTH") + "%")}));
        //技术检测
        category.add(mapper("NAME", "技术检测", "AMOUNT", data.get("TECHNICAL_INSPECTION"), "RATE", data.get("TECHNICAL_INSPECTION_RATE"), "TIMES", 0, "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("TECHNICAL_MONTHONMONTH") + "%")}));
        result.put("CATEGORY", category);
        return data;
    }

    /**
     * 数据处理(月)
     *
     * @param result
     * @param data
     * @return
     */
    public JSONObject processDataMonth(JSONObject result, JSONObject data, JSONObject param) {
        JSONArray category = new JSONArray();
        JSONArray salesReportDay = SpringManager.getBean(SalesReportDao.class).findSalesReportMonth(param);

        //洗车
        category.add(mapper("NAME", "洗车", "AMOUNT", data.get("CAR_WASH"), "RATE", data.get("CAR_WASH_RATE"), "TIMES", data.get("CAR_WASH_TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("CAR_WASH_MONTHONMONTH") + "%")}, "PROFIT_R", findServerType(salesReportDay, "001").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "001").getString("PROFIT")));
        //美容
        category.add(mapper("NAME", "美容", "AMOUNT", data.get("COSMETOLOGY"), "RATE", data.get("COSMETOLOGY_RATE"), "TIMES", data.get("COSMETOLOGY_TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("COSMETOLOGY_MONTHONMONTH") + "%")}, "PROFIT_R", findServerType(salesReportDay, "002").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "002").getString("PROFIT")));
        //保养
        category.add(mapper("NAME", "保养", "AMOUNT", data.get("MAINTAIN"), "RATE", data.get("MAINTAIN_RATE"), "TIMES", data.get("MAINTAIN_TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("MAINTAIN_MONTHONMONTH") + "%")}, "PROFIT_R", findServerType(salesReportDay, "003").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "003").getString("PROFIT")));
        //维修
        category.add(mapper("NAME", "维修", "AMOUNT", data.get("REPAIR"), "RATE", data.get("REPAIR_RATE"), "TIMES", data.get("REPAIR_TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("REPAIR_MONTHONMONTH") + "%")}, "PROFIT_R", findServerType(salesReportDay, "004").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "004").getString("PROFIT")));
        //钣喷
        category.add(mapper("NAME", "钣喷", "AMOUNT", data.get("SHEET_METAL_SPRAY"), "RATE", data.get("SHEET_METAL_SPRAY_RATE"), "TIMES", data.get("SHEET_METAL_SPRAY_TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("SHEET_METAL_SPRAY_MONTHONMONTH") + "%")}, "PROFIT_R", findServerType(salesReportDay, "007").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "007").getString("PROFIT")));
        //改装
        category.add(mapper("NAME", "改装", "AMOUNT", data.get("REFIT"), "RATE", data.get("REFIT_RATE"), "TIMES", findServerType(salesReportDay, "005").get("TIMES"), "ITEM", new Object[]{mapper("LABEL", "台次", "VALUE", data.get("REFIT_TIMES")), mapper("LABEL", "环比", "VALUE", data.get("REFIT_MONTHONMONTH") + "%")}, "PROFIT_R", findServerType(salesReportDay, "005").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "005").getString("PROFIT")));
        //年卡
//        category.add(mapper("NAME", "年卡", "YEARCARD", data.get("YEARCARD"), "BUY_YEARCARD", data.get("BUY_YEARCARD"), "ITEM", new Object[]{}));
        //轮胎
        category.add(mapper("NAME", "轮胎", "AMOUNT", data.get("TYRE"), "RATE", data.get("TYRE_RATE"), "TIMES", data.get("TYRE_TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("TYRE_MONTHONMONTH") + "%")}, "PROFIT_R", findServerType(salesReportDay, "021").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "021").getString("PROFIT")));
        //精品
        category.add(mapper("NAME", "精品", "AMOUNT", data.get("BOUTIQUE"), "RATE", data.get("BOUTIQUE_RATE"), "TIMES", findServerType(salesReportDay, "006").get("TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("BOUTIQUE_MONTHONMONTH") + "%")}, "PROFIT_R", findServerType(salesReportDay, "006").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "006").getString("PROFIT")));
        //生活用品
        category.add(mapper("NAME", "生活用品", "AMOUNT", data.get("ARTICLES_FOR_DAILY_USE"), "RATE", data.get("ARTICLES_FOR_DAILY_USE_RATE"), "TIMES", findServerType(salesReportDay, "009").get("TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("ARTICLES_MONTHONMONTH") + "%")}, "PROFIT_R", findServerType(salesReportDay, "009").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "009").getString("PROFIT")));
        //道路救援
        category.add(mapper("NAME", "道路救援金额", "AMOUNT", data.get("ROAD_RESCUE"), "RATE", data.get("ROAD_RESCUE_RATE"), "TIMES", data.get("ROAD_RESCUE_TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("ROAD_RESCUE_MONTHONMONTH") + "%")}, "PROFIT_R", findServerType(salesReportDay, "008").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "008").getString("PROFIT")));
        //信息服务
        category.add(mapper("NAME", "信息服务", "AMOUNT", data.get("INFORMATION_SERVICE"), "RATE", data.get("INFORMATION_SERVICE_RATE"), "TIMES", findServerType(salesReportDay, "020").get("TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("INFORMATION_MONTHONMONTH") + "%")}, "PROFIT_R", findServerType(salesReportDay, "020").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "020").getString("PROFIT")));
        //技术检测
        category.add(mapper("NAME", "技术检测", "AMOUNT", data.get("TECHNICAL_INSPECTION"), "RATE", data.get("TECHNICAL_INSPECTION_RATE"), "TIMES", findServerType(salesReportDay, "024").get("TIMES"), "ITEM", new Object[]{mapper("LABEL", "环比", "VALUE", data.get("TECHNICAL_MONTHONMONTH") + "%")}, "PROFIT_R", findServerType(salesReportDay, "024").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "024").getString("PROFIT")));
        result.put("CATEGORY", category.stream().sorted(Comparator.comparing(o -> (BigDecimal) ((Map) o).get("AMOUNT")).reversed()).collect(Collectors.toList()));
        return data;
    }

    /**
     * 数据处理(日)
     *
     * @param result
     * @param data
     * @return
     */
    public JSONObject processDataDay(JSONObject result, JSONObject data) {
        JSONArray category = new JSONArray();
        //洗车
        category.add(mapper("NAME", "洗车", "AMOUNT", data.get("CAR_WASH"), "RATE", data.get("CAR_WASH_RATE"), "TIMES", data.get("CAR_WASH_TIMES"), "ITEM", new Object[]{}));
        //美容
        category.add(mapper("NAME", "美容", "AMOUNT", data.get("COSMETOLOGY"), "RATE", data.get("COSMETOLOGY_RATE"), "TIMES", data.get("COSMETOLOGY_TIMES"), "ITEM", new Object[]{}));
        //保养
        category.add(mapper("NAME", "保养", "AMOUNT", data.get("MAINTAIN"), "RATE", data.get("MAINTAIN_RATE"), "TIMES", data.get("MAINTAIN_TIMES"), "ITEM", new Object[]{}));
        //维修
        category.add(mapper("NAME", "维修", "AMOUNT", data.get("REPAIR"), "RATE", data.get("REPAIR_RATE"), "TIMES", data.get("REPAIR_TIMES"), "ITEM", new Object[]{}));
        //钣喷
        category.add(mapper("NAME", "钣喷", "AMOUNT", data.get("SHEET_METAL_SPRAY"), "RATE", data.get("SHEET_METAL_SPRAY_RATE"), "TIMES", data.get("SHEET_METAL_SPRAY_TIMES"), "ITEM", new Object[]{}));
        //改装
        category.add(mapper("NAME", "改装", "AMOUNT", data.get("REFIT"), "RATE", data.get("REFIT_RATE"), "TIMES", data.get("REFIT_TIMES"), "ITEM", new Object[]{}));
        //年卡
//        category.add(mapper("NAME", "年卡", "YEARCARD", data.get("YEARCARD"), "BUY_YEARCARD", data.get("BUY_YEARCARD"), "ITEM", new Object[]{}));
        //轮胎
        category.add(mapper("NAME", "轮胎", "AMOUNT", data.get("TYRE"), "RATE", data.get("TYRE_RATE"), "TIMES", data.get("TYRE_TIMES"), "ITEM", new Object[]{}));
        //精品
        category.add(mapper("NAME", "精品", "AMOUNT", data.get("BOUTIQUE"), "RATE", data.get("BOUTIQUE_RATE"), "TIMES", 0, "ITEM", new Object[]{}));
        //生活用品
        category.add(mapper("NAME", "生活用品", "AMOUNT", data.get("ARTICLES_FOR_DAILY_USE"), "RATE", data.get("ARTICLES_FOR_DAILY_USE_RATE"), "TIMES", 0, "ITEM", new Object[]{}));
        //道路救援
        category.add(mapper("NAME", "道路救援金额", "AMOUNT", data.get("ROAD_RESCUE"), "RATE", data.get("ROAD_RESCUE_RATE"), "TIMES", data.get("ROAD_RESCUE_TIMES"), "ITEM", new Object[]{}));
        //信息服务
        category.add(mapper("NAME", "信息服务", "AMOUNT", data.get("INFORMATION_SERVICE"), "RATE", data.get("INFORMATION_SERVICE_RATE"), "TIMES", 0, "ITEM", new Object[]{}));
        //技术检测
        category.add(mapper("NAME", "技术检测", "AMOUNT", data.get("TECHNICAL_INSPECTION"), "RATE", data.get("TECHNICAL_INSPECTION_RATE"), "TIMES", 0, "ITEM", new Object[]{}));
        result.put("CATEGORY", category);
        return data;
    }

    /**
     * 数据处理(日)插入新数据
     *
     * @param result
     * @param data
     * @return
     */
    public JSONObject processDataDayInset(JSONObject result, JSONObject data, JSONObject param) {
        JSONArray salesReportDay = SpringManager.getBean(SalesReportDao.class).findSalesReportDay(param);
        JSONArray category = new JSONArray();
        //洗车
        category.add(mapper("NAME", "洗车", "AMOUNT", data.get("CAR_WASH"), "RATE", data.get("CAR_WASH_RATE"), "TIMES", data.get("CAR_WASH_TIMES"), "ITEM", new Object[]{}, "PROFIT_R", findServerType(salesReportDay, "001").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "001").getString("PROFIT")));
        //美容
        category.add(mapper("NAME", "美容", "AMOUNT", data.get("COSMETOLOGY"), "RATE", data.get("COSMETOLOGY_RATE"), "TIMES", data.get("COSMETOLOGY_TIMES"), "ITEM", new Object[]{}, "PROFIT_R", findServerType(salesReportDay, "002").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "002").getString("PROFIT")));
        //保养
        category.add(mapper("NAME", "保养", "AMOUNT", data.get("MAINTAIN"), "RATE", data.get("MAINTAIN_RATE"), "TIMES", data.get("MAINTAIN_TIMES"), "ITEM", new Object[]{}, "PROFIT_R", findServerType(salesReportDay, "003").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "003").getString("PROFIT")));
        //维修
        category.add(mapper("NAME", "维修", "AMOUNT", data.get("REPAIR"), "RATE", data.get("REPAIR_RATE"), "TIMES", data.get("REPAIR_TIMES"), "ITEM", new Object[]{}, "PROFIT_R", findServerType(salesReportDay, "004").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "004").getString("PROFIT")));
        //钣喷
        category.add(mapper("NAME", "钣喷", "AMOUNT", data.get("SHEET_METAL_SPRAY"), "RATE", data.get("SHEET_METAL_SPRAY_RATE"), "TIMES", data.get("SHEET_METAL_SPRAY_TIMES"), "ITEM", new Object[]{}, "PROFIT_R", findServerType(salesReportDay, "007").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "007").getString("PROFIT")));
        //改装
        category.add(mapper("NAME", "改装", "AMOUNT", data.get("REFIT"), "RATE", data.get("REFIT_RATE"), "TIMES", data.get("REFIT_TIMES"), "ITEM", new Object[]{}, "PROFIT_R", findServerType(salesReportDay, "005").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "005").getString("PROFIT")));
        //年卡
//        category.add(mapper("NAME", "年卡", "YEARCARD", data.get("YEARCARD"), "BUY_YEARCARD", data.get("BUY_YEARCARD"), "ITEM", new Object[]{}));
        //轮胎
        category.add(mapper("NAME", "轮胎", "AMOUNT", data.get("TYRE"), "RATE", data.get("TYRE_RATE"), "TIMES", data.get("TYRE_TIMES"), "ITEM", new Object[]{}, "PROFIT_R", findServerType(salesReportDay, "021").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "021").getString("PROFIT")));
        //精品
        category.add(mapper("NAME", "精品", "AMOUNT", data.get("BOUTIQUE"), "RATE", data.get("BOUTIQUE_RATE"), "TIMES", findServerType(salesReportDay, "006").get("TIMES"), "ITEM", new Object[]{}, "PROFIT_R", findServerType(salesReportDay, "006").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "006").getString("PROFIT")));
        //生活用品
        category.add(mapper("NAME", "生活用品", "AMOUNT", data.get("ARTICLES_FOR_DAILY_USE"), "RATE", data.get("ARTICLES_FOR_DAILY_USE_RATE"), "TIMES", findServerType(salesReportDay, "009").get("TIMES"), "ITEM", new Object[]{}, "PROFIT_R", findServerType(salesReportDay, "009").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "009").getString("PROFIT")));
        //道路救援
        category.add(mapper("NAME", "道路救援金额", "AMOUNT", data.get("ROAD_RESCUE"), "RATE", data.get("ROAD_RESCUE_RATE"), "TIMES", data.get("ROAD_RESCUE_TIMES"), "ITEM", new Object[]{}, "PROFIT_R", findServerType(salesReportDay, "008").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "008").getString("PROFIT")));
        //信息服务
        category.add(mapper("NAME", "信息服务", "AMOUNT", data.get("INFORMATION_SERVICE"), "RATE", data.get("INFORMATION_SERVICE_RATE"), "TIMES", findServerType(salesReportDay, "020").get("TIMES"), "ITEM", new Object[]{}, "PROFIT_R", findServerType(salesReportDay, "020").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "020").getString("PROFIT")));
        //技术检测
        category.add(mapper("NAME", "技术检测服务", "AMOUNT", data.get("TECHNICAL_INSPECTION"), "RATE", data.get("TECHNICAL_INSPECTION_RATE"), "TIMES", findServerType(salesReportDay, "024").get("TIMES"), "ITEM", new Object[]{}, "PROFIT_R", findServerType(salesReportDay, "024").getString("PROFIT_R"), "PROFIT", findServerType(salesReportDay, "024").getString("PROFIT")));
        result.put("CATEGORY", category.stream().sorted(Comparator.comparing(o -> (BigDecimal) ((Map) o).get("AMOUNT")).reversed()).collect(Collectors.toList()));
        return data;
    }

    private JSONObject findServerType(JSONArray salesReportDay, String s) {
        JSONObject jsonObject = salesReportDay.stream().map(o -> (JSONObject) o).filter(o -> o.getString("SERVE_TYPE_ID").equals(s)).findFirst().orElse(null);
        if (jsonObject == null) jsonObject = new JSONObject();
        if (jsonObject.isEmpty()) {
            jsonObject.put("TIMES", 0);
            jsonObject.put("PROFIT_R", 0);
            jsonObject.put("PROFIT", 0);
        }
        return jsonObject;
    }

    /**
     * 查询应收账款(外)
     *
     * @param request
     * @return
     */
    public Map find_receivableOut(SimpleRequest request) throws ParseException {
        JSONObject param = this.checkRequest(request);
        JSONArray payment = null;
        if (param.size() > 0) {
            payment = reportDaliyDao.find_receivableOut(param);
            payment.forEach(pay -> {
                JSONObject jsonObject = (JSONObject) pay;
                Object date_of_statistics = param.get("DATE_OF_STATISTICS");
                if (date_of_statistics != null && param.get("DATE_APPROVE") == null) {
                    jsonObject.put("DATE_OF_STATISTICS", date_of_statistics);
                }
                if (param.get("DATE_APPROVE") != null && date_of_statistics != null) {
                    try {
                        JSONArray date = (JSONArray) date_of_statistics;
                        JSONArray date_statistics = findRangeDateFromStartDateAndEndDate((String) param.get("DATE_APPROVE"),(String) date.get(0),(String) date.get(1),DateUtil.SHOW_DATETIME_UTC_FORMAT);

                        jsonObject.put("DATE_OF_STATISTICS", date_statistics);

                    } catch (Exception e) {

                        jsonObject.put("DATE_OF_STATISTICS", date_of_statistics);
                    }
                }

            });
        } else {
            JSONObject param1 = request.get("data");
            JSONObject param2 = new JSONObject();
            JSONArray array = new JSONArray();
            array.add(DateUtil.format(param1.getDate("reconcileBeginDate"), DateUtil.SHOW_DATETIME_UTC_FORMAT));
            array.add(DateUtil.format(param1.getDate("reconcileEndDate"), DateUtil.SHOW_DATETIME_UTC_FORMAT));
            param2.put("DATE_OF_STATISTICS", array);
            param2.put("COMPANY_ID", param1.getJSONObject("merchant").get("id").toString());
            payment = reportDaliyDao.find_receivableOut(param2);
            payment.forEach(pay -> {
                JSONObject jsonObject = (JSONObject) pay;
                if (param2.get("DATE_OF_STATISTICS") != null) {
                    jsonObject.put("DATE_OF_STATISTICS", param2.get("DATE_OF_STATISTICS"));
                }
                if (param2.get("DATE_OF_STATISTICS") != null) {
                    try {
                        jsonObject.put("DATE_APPROVE", param2.get("DATE_OF_STATISTICS"));
                    } catch (Exception e) {
                        jsonObject.put("DATE_OF_STATISTICS", param2.get("DATE_OF_STATISTICS"));
                    }
                }

            });
        }

        return packageReturnArray(payment);
    }

    /**
     * 查询应收账款(外)明细
     *
     * @param request
     * @return
     */
    public JSONObject findReceivableOutMx(SimpleRequest request) throws ParseException {
        JSONObject param = this.checkRequest(request);
        JSONObject object = new JSONObject();
        JSONArray tableHeader = new JSONArray();
        Map DATE_OF_STATISTICS = MapUtil.mapper("field", "DATE_OF_STATISTICS",
                "headerName", "统计日期", "width", 110
        );
        tableHeader.add(DATE_OF_STATISTICS);
        Map DEPT_NAME = MapUtil.mapper("field", "DEPT_NAME",
                "headerName", "部门名称", "width", 220
        );
        tableHeader.add(DEPT_NAME);
        Map api = MapUtil.mapper("api", "rcl.businessAmt.receivableOutMxGdj");
        Map AMOUNT = MapUtil.mapper("field", "AMOUNT",
                "headerName", "营业额", "width", 130, "sum", true, "cellRenderer", "link", "cellEditorParams", api
        );
        tableHeader.add(AMOUNT);


        Map COMPANY_NAME = MapUtil.mapper("field", "COMPANY_NAME",
                "headerName", "公司名称", "width", 280
        );
        tableHeader.add(COMPANY_NAME);

        Map CUSTOMER_NAME = MapUtil.mapper("field", "CUSTOMER_NAME",
                "headerName", "客户名称", "width", 280
        );
        tableHeader.add(CUSTOMER_NAME);

        JSONArray array = reportDaliyDao.find_receivableOutMx(param);

        object.put("tableHeader", tableHeader);
        object.put("content", array);
        return object;
    }

    /**
     * 查询应收账款(外)明细
     *
     * @param request
     * @return
     */
    public Map find_receivableOutMx(SimpleRequest request) throws ParseException {
        JSONObject param = this.checkRequest(request);
//        JSONObject object = new JSONObject();
//        object.put("content", reportDaliyDao.find_receivableOutMx(param));
//        JSONObject model =  SpringManager.getBean(MerchantReconciliationService.class).checkRequest(request);
        return packageReturnArray(reportDaliyDao.find_receivableOutMx(param));
    }


    /**
     * 应收账款内（包含定损介绍费)
     *
     * @param request
     * @return
     */
    public Map find_receivableIn(SimpleRequest request) throws ParseException {
        JSONObject param = this.checkRequest(request);
        JSONArray payment = null;
        if (param.size() > 0) {
            payment = reportDaliyDao.find_receivableIn(param);
            payment.forEach(pay -> {
                JSONObject jsonObject = (JSONObject) pay;
                Object date_of_statistics = param.get("DATE_OF_STATISTICS");
                if (date_of_statistics != null && param.get("DATE_APPROVE") == null) {
                    jsonObject.put("DATE_OF_STATISTICS", date_of_statistics);
                }
                if (param.get("DATE_APPROVE") != null && date_of_statistics != null) {
                    try {
                        JSONArray date = (JSONArray) date_of_statistics;
                        JSONArray date_statistics = findRangeDateFromStartDateAndEndDate((String) param.get("DATE_APPROVE"),(String) date.get(0),(String) date.get(1),DateUtil.SHOW_DATETIME_UTC_FORMAT);

                        jsonObject.put("DATE_APPROVE", date_statistics);

                    } catch (Exception e) {

                        jsonObject.put("DATE_OF_STATISTICS", date_of_statistics);
                    }
                }

            });
        } else {
            JSONObject param1 = request.get("data");
            JSONObject param2 = new JSONObject();
            JSONArray array = new JSONArray();
            array.add(DateUtil.format(param1.getDate("reconcileBeginDate"), DateUtil.SHOW_DATETIME_UTC_FORMAT));
            array.add(DateUtil.format(param1.getDate("reconcileEndDate"), DateUtil.SHOW_DATETIME_UTC_FORMAT));
            param2.put("DATE_OF_STATISTICS", array);
            param2.put("COMPANY_ID", param1.getJSONObject("merchant").get("id").toString());
            payment = reportDaliyDao.find_receivableIn(param2);
            payment.forEach(pay -> {
                JSONObject jsonObject = (JSONObject) pay;
                if (param2.get("DATE_OF_STATISTICS") != null) {
                    jsonObject.put("DATE_OF_STATISTICS", param2.get("DATE_OF_STATISTICS"));
                }
                if (param2.get("DATE_OF_STATISTICS") != null) {
                    try {
                        jsonObject.put("DATE_APPROVE", param2.get("DATE_OF_STATISTICS"));
                    } catch (Exception e) {
                        jsonObject.put("DATE_OF_STATISTICS", param2.get("DATE_OF_STATISTICS"));
                    }
                }

            });
        }

        return packageReturnArray(payment);
    }

    /**
     * 查询应收账款(内)明细
     *
     * @param request
     * @return
     */
    public JSONObject findReceivableInMx(SimpleRequest request) throws ParseException {
        JSONObject param = this.checkRequest(request);
        JSONObject object = new JSONObject();
        JSONArray tableHeader = new JSONArray();
        Map DATE_OF_STATISTICS = MapUtil.mapper("field", "DATE_OF_STATISTICS",
                "headerName", "统计日期", "width", 110
        );
        tableHeader.add(DATE_OF_STATISTICS);
        Map DEPT_NAME = MapUtil.mapper("field", "DEPT_NAME",
                "headerName", "部门名称", "width", 220
        );
        tableHeader.add(DEPT_NAME);

        Map TYPE = MapUtil.mapper("field", "ACCOUNTTYPE",
                "headerName", "挂账类型", "width", 90
        );
        tableHeader.add(TYPE);
        Map api = MapUtil.mapper("api", "rcl.businessAmt.receivableInMxGdj");
        Map AMOUNT = MapUtil.mapper("field", "AMOUNT",
                "headerName", "营业额", "width", 130, "sum", true, "cellRenderer", "link", "cellEditorParams", api
        );
        tableHeader.add(AMOUNT);


        Map COMPANY_NAME = MapUtil.mapper("field", "COMPANY_NAME",
                "headerName", "公司名称", "width", 280
        );
        tableHeader.add(COMPANY_NAME);

        JSONArray array = reportDaliyDao.find_receivableInMx(param);

        object.put("tableHeader", tableHeader);
        object.put("content", array);
        return object;
    }


    /**
     * 查询应收账款(内)明细
     *
     * @param request
     * @return
     */
    public Map find_receivableInMx(SimpleRequest request) throws ParseException {
        JSONObject param = this.checkRequest(request);
//        JSONObject object = new JSONObject();
//        object.put("content", reportDaliyDao.find_receivableInMx(param));
//        JSONObject model =  SpringManager.getBean(MerchantReconciliationService.class).checkRequest(request);
        return packageReturnArray(reportDaliyDao.find_receivableInMx(param));
    }


    /**
     * 查询应收账款(外)明细_各单据
     *
     * @param request
     * @return
     */
    public JSONObject find_receivableOutMxGdj(SimpleRequest request) {
        JSONObject param = this.checkRequest(request);
        JSONObject object = new JSONObject();
        JSONArray tableHeader = new JSONArray();
        Map DATE_OF_STATISTICS = MapUtil.mapper("field", "DATE_OF_STATISTICS",
                "headerName", "日期", "width", 110
        );
        tableHeader.add(DATE_OF_STATISTICS);
        Map DEPT_ID = MapUtil.mapper("field", "DEPT_ID",
                "headerName", "门店", "width", 100
        );
        tableHeader.add(DEPT_ID);
        Map DEPT_NAME = MapUtil.mapper("field", "DEPT_NAME",
                "headerName", "门店名称", "width", 220
        );
        tableHeader.add(DEPT_NAME);

        Map CAR_LICENSE = MapUtil.mapper("field", "CAR_LICENSE",
                "headerName", "车牌", "width", 90
        );
        tableHeader.add(CAR_LICENSE);
//        Map MOBILE = MapUtil.mapper("field", "MOBILE",
//                "headerName", "手机号", "width", 120
//        );
//        tableHeader.add(MOBILE);
        Map BUSINESS_ID = MapUtil.mapper("field", "ID",
                "headerName", "单号", "width", 90, "cellRenderer", "dialogButton", "buttonList", "[\n" +
                        "                           {\n" +
                        "                           'id':'search',\n" +
                        "                           'name':'',\n" +
                        "                           'hide':'false',\n" +
                        "                           'disabled':'false',\n" +
                        "                           'action': 'link',\n" +
                        "                           'link':'true'," +
                        "                           'api':'form/retail.order',\n" +
                        "                           'config':{'OAInterface':false,'api':'retail.order.findOne'}\n" +
                        "                           }]"
        );
        tableHeader.add(BUSINESS_ID);
        Map INNER_BUSINESS_TYPE = MapUtil.mapper("field", "INNER_BUSINESS_TYPE",
                "headerName", "单据类型", "width", 90
        );
        tableHeader.add(INNER_BUSINESS_TYPE);
        Map AMOUNT = MapUtil.mapper("field", "AMOUNT",
                "headerName", "收款金额", "width", 90, "sum", true
        );
        tableHeader.add(AMOUNT);
        Map PAYMENT_METHOD_TYPE_NAME = MapUtil.mapper("field", "PAYMENT_METHOD_TYPE_NAME",
                "headerName", "收款方式", "width", 100
        );
        tableHeader.add(PAYMENT_METHOD_TYPE_NAME);
        Map CUSTOMER_ID = MapUtil.mapper("field", "CUSTOMER_ID",
                "headerName", "客户编码", "width", 90
        );
        tableHeader.add(CUSTOMER_ID);
        Map CUSTOMER_NAME = MapUtil.mapper("field", "CUSTOMER_NAME",
                "headerName", "客户", "width", 250
        );
        Map SOURCE_BUSINESS_TYPE = MapUtil.mapper("field", "SOURCE_BUSINESS_TYPE",
                "headerName", "来源单据", "width", 160
        );
        tableHeader.add(SOURCE_BUSINESS_TYPE);
        Map SOURCE_ID = MapUtil.mapper("field", "SOURCE_ID",
                "headerName", "来源单据号", "width", 120
        );
        tableHeader.add(SOURCE_ID);
        tableHeader.add(CUSTOMER_NAME);

        JSONArray array = reportDaliyDao.find_receivableOutMxGdj(param);

        object.put("tableHeader", tableHeader);
        object.put("content", array);
//        JSONObject model =  SpringManager.getBean(MerchantReconciliationService.class).checkRequest(request);
        return object;
    }


    /**
     * 查询应收账款(内)明细_各单据
     *
     * @param request
     * @return
     */
    public JSONObject find_receivableInMxGdj(SimpleRequest request) {
        JSONObject param = this.checkRequest(request);
        String ACCOUNTTYPE = param.getString("ACCOUNTTYPE");
        if (ACCOUNTTYPE.equals("集群引流") || ACCOUNTTYPE.equals("其他")) {
            return find_receivableInMxByRetailOrder(param);
        } else if (ACCOUNTTYPE.equals("兑换券置换")) {
            return find_receivableInMxByRetailOrder(param);
        } else if (ACCOUNTTYPE.equals("定损介绍费")) {
            return find_receivableInMxByExpense(param);
        } else if (ACCOUNTTYPE.equals("平台内客户")) {
            return find_receivableInMxByVoucher(param);
        } else if (ACCOUNTTYPE.equals("管理服务费")) {
            return find_receivableInMxBycommission(param);
        } else if (ACCOUNTTYPE.equals("二手车服务费")) {
            return find_receivableInMxByUsedCar(param);
        } else if (ACCOUNTTYPE.equals("e服务+")) {
            return find_eServicesPlus(param);
        } else if (ACCOUNTTYPE.equals("e服务")) {
            return find_eServices(param);
        }
        return null;
    }

    public JSONObject find_receivableInMxByUsedCar(JSONObject param) {
        JSONObject object = new JSONObject();
        JSONArray tableHeader = new JSONArray();
        Map DATE_OF_STATISTICS = MapUtil.mapper("field", "DATE_OF_STATISTICS",
                "headerName", "统计日期", "width", 90
        );
        Map DEPT_NAME = MapUtil.mapper("field", "DEPT_NAME",
                "headerName", "门店", "sum", "true", "width", 80
        );

        Map LICENSE_PLATE = MapUtil.mapper("field", "LICENSE_PLATE",
                "headerName", "车牌", "width", 90
        );
        Map FINAL_PRICE = MapUtil.mapper("field", "FINAL_PRICE",
                "headerName", "成交价", "width", 90
        );
        Map AMOUNT = MapUtil.mapper("field", "AMOUNT",
                "headerName", "二手车服务费", "width", 90
        );

        tableHeader.add(DATE_OF_STATISTICS);
        tableHeader.add(DEPT_NAME);
        tableHeader.add(LICENSE_PLATE);
        tableHeader.add(FINAL_PRICE);
        tableHeader.add(AMOUNT);
        JSONArray array = reportDaliyDao.find_receivableInMxByUsedCar(param);

        object.put("tableHeader", tableHeader);
        object.put("content", array);
//        JSONObject model =  SpringManager.getBean(MerchantReconciliationService.class).checkRequest(request);
        return object;
    }


    /**
     * 集群引流 / 其他
     *
     * @param param
     * @return
     */
    public JSONObject find_receivableInMxByRetailOrder(JSONObject param) {
        JSONObject object = new JSONObject();
        JSONArray tableHeader = new JSONArray();
        Map DATE_OF_STATISTICS = MapUtil.mapper("field", "DATE_OF_STATISTICS",
                "headerName", "日期", "width", 110
        );
        tableHeader.add(DATE_OF_STATISTICS);
        Map DEPT_ID = MapUtil.mapper("field", "DEPT_ID",
                "headerName", "门店", "width", 90
        );
        tableHeader.add(DEPT_ID);
        Map DEPT_NAME = MapUtil.mapper("field", "DEPT_NAME",
                "headerName", "门店名称", "width", 200
        );
        tableHeader.add(DEPT_NAME);
        Map SOURCE_BUSINESS_TYPE = MapUtil.mapper("field", "SOURCE_BUSINESS_TYPE",
                "headerName", "来源单据", "width", 90
        );
        tableHeader.add(SOURCE_BUSINESS_TYPE);
        Map SOURCE_ID = MapUtil.mapper("field", "ID",
                "headerName", "零售单号", "width", 90, "cellRenderer", "dialogButton", "buttonList", "[\n" +
                        "                           {\n" +
                        "                           'id':'search',\n" +
                        "                           'name':'查详情',\n" +
                        "                           'hide':'false',\n" +
                        "                           'disabled':'false',\n" +
                        "                           'action': 'link',\n" +
                        "                           'link':'true'," +
                        "                           'api':'form/retail.order',\n" +
                        "                           'config':{'OAInterface':false,'api':'retail.order.findOne'}\n" +
                        "                           }]"
        );
        tableHeader.add(SOURCE_ID);
        Map CAR_LICENSE = MapUtil.mapper("field", "CAR_LICENSE",
                "headerName", "车牌", "width", 90
        );
        tableHeader.add(CAR_LICENSE);
//        Map MOBILE = MapUtil.mapper("field", "MOBILE",
//                "headerName", "手机号", "width", 120
//        );
//        tableHeader.add(MOBILE);
        Map AMOUNT = MapUtil.mapper("field", "AMOUNT",
                "headerName", "收款金额", "width", 80, "sum", "true"
        );
        tableHeader.add(AMOUNT);
        Map PAYMENT_METHOD_TYPE_NAME = MapUtil.mapper("field", "PAYMENT_METHOD_TYPE_NAME",
                "headerName", "收款方式", "width", 90
        );
        tableHeader.add(PAYMENT_METHOD_TYPE_NAME);
        Map CUSTOMER_ID = MapUtil.mapper("field", "CUSTOMER_ID",
                "headerName", "客户编码", "width", 90
        );
        tableHeader.add(CUSTOMER_ID);
        Map CUSTOMER_NAME = MapUtil.mapper("field", "CUSTOMER_NAME",
                "headerName", "客户", "width", 220
        );
        tableHeader.add(CUSTOMER_NAME);
        Map CROSSIC_NAME = MapUtil.mapper("field", "CROSSIC_NAME",
                "headerName", "异业合作客户", "width", 220
        );
        tableHeader.add(CROSSIC_NAME);
        Map COMPANY_NAME = MapUtil.mapper("field", "COMPANY_NAME",
                "headerName", "公司", "width", 280
        );
        tableHeader.add(COMPANY_NAME);

        JSONArray array = reportDaliyDao.find_receivableInMxGdj(param);

        object.put("tableHeader", tableHeader);
        object.put("content", array);
//        JSONObject model =  SpringManager.getBean(MerchantReconciliationService.class).checkRequest(request);
        return object;
    }


    /**
     * e服务+
     *
     * @param param
     * @return
     */
    private JSONObject find_eServicesPlus(JSONObject param) {
        JSONObject object = new JSONObject();
        JSONArray tableHeader = new JSONArray();
        Map DATE_OF_STATISTICS = MapUtil.mapper("field", "DATE_OF_STATISTICS",
                "headerName", "收款日期", "width", 110
        );
        tableHeader.add(DATE_OF_STATISTICS);
        Map DEPT_NAME = MapUtil.mapper("field", "DEPT_NAME",
                "headerName", "门店名称", "width", 200
        );
        tableHeader.add(DEPT_NAME);
        Map SOURCE_BUSINESS_TYPE = MapUtil.mapper("field", "SOURCE_BUSINESS_TYPE",
                "headerName", "单据类型", "width", 90
        );
        tableHeader.add(SOURCE_BUSINESS_TYPE);
        Map SOURCE_ID = MapUtil.mapper("field", "ID",
                "headerName", "单据号", "width", 130, "cellRenderer", "dialogButton", "buttonList", "[\n" +
                        "                           {\n" +
                        "                           'id':'search',\n" +
                        "                           'name':'查详情',\n" +
                        "                           'hide':'false',\n" +
                        "                           'disabled':'false',\n" +
                        "                           'action': 'link',\n" +
                        "                           'link':'true'," +
                        "                           'api':'form/retail.order',\n" +
                        "                           'config':{'OAInterface':false,'api':'retail.order.findOne'}\n" +
                        "                           }]"
        );
        tableHeader.add(SOURCE_ID);

        Map AMOUNT = MapUtil.mapper("field", "AMOUNT",
                "headerName", "收款金额", "width", 90, "sum", "true"
        );
        tableHeader.add(AMOUNT);

        Map CUSTOMER_ID = MapUtil.mapper("field", "CUSTOMER_ID",
                "headerName", "客户编码", "width", 90
        );
        tableHeader.add(CUSTOMER_ID);
        Map CUSTOMER_NAME = MapUtil.mapper("field", "CUSTOMER_NAME",
                "headerName", "客户名称", "width", 220
        );
        tableHeader.add(CUSTOMER_NAME);

        Map CROSSIC_NAME = MapUtil.mapper("field", "CAR_LICENSE",
                "headerName", "车牌", "width", 90
        );
        tableHeader.add(CROSSIC_NAME);

        Map COMPANY_NAME = MapUtil.mapper("field", "COMPANY_NAME",
                "headerName", "公司", "width", 280
        );
        tableHeader.add(COMPANY_NAME);


        JSONArray array = reportDaliyDao.find_eServicePlus(param);

        object.put("tableHeader", tableHeader);
        object.put("content", array);
        return object;
    }

    /**
     * e服务
     *
     * @param param
     * @return
     */
    private JSONObject find_eServices(JSONObject param) {
        JSONObject object = new JSONObject();
        JSONArray tableHeader = new JSONArray();
        Map DATE_APPROVE = MapUtil.mapper("field", "DATE_APPROVE",
                "headerName", "收款日期", "width", 90
        );
        tableHeader.add(DATE_APPROVE);
        Map DEPT_NAME = MapUtil.mapper("field", "DEPT_NAME",
                "headerName", "门店", "width", 120
        );

        tableHeader.add(DEPT_NAME);
        Map ID = MapUtil.mapper("field", "ID",
                "headerName", "凭证单号", "width", 130, "cellRenderer", "dialogButton", "buttonList", "[\n" +
                        "                           {\n" +
                        "                           'id':'search',\n" +
                        "                           'name':'详情',\n" +
                        "                           'hide':'false',\n" +
                        "                           'disabled':'false',\n" +
                        "                           'action': 'link',\n" +
                        "                           'link':'true'," +
                        "                           'api':'form/purch.voucher',\n" +
                        "                           'config':{'OAInterface':false,'api':'voucher.findOne'}\n" +
                        "                           }]"
        );
        tableHeader.add(ID);
        Map ORIGIN_BUSINESS_TYPE = MapUtil.mapper("field", "ORIGIN_BUSINESS_TYPE",
                "headerName", "源单据", "width", 100
        );
        tableHeader.add(ORIGIN_BUSINESS_TYPE);
        Map ORIGIN = MapUtil.mapper("field", "ORIGIN",
                "headerName", "源单据号", "width", 140
        );
        tableHeader.add(ORIGIN);

        Map AMOUNT = MapUtil.mapper("field", "AMOUNT",
                "headerName", "收款金额", "sum", "true", "width", 90
        );
        tableHeader.add(AMOUNT);
        Map CUSTOMER_ID = MapUtil.mapper("field", "CUSTOMER_ID",
                "headerName", "客户编码", "width", 90
        );
        tableHeader.add(CUSTOMER_ID);


        Map CUSTOMER_NAME = MapUtil.mapper("field", "CUSTOMER_NAME",
                "headerName", "客户", "width", 120
        );
        tableHeader.add(CUSTOMER_NAME);
        Map CAR_LICENSE = MapUtil.mapper("field", "CAR_LICENSE",
                "headerName", "车牌", "width", 120
        );
        tableHeader.add(CAR_LICENSE);
        Map COMPANY_NAME = MapUtil.mapper("field", "COMPANY_NAME",
                "headerName", "公司", "width", 120
        );
        tableHeader.add(COMPANY_NAME);
        JSONArray array = reportDaliyDao.find_eService(param);
        object.put("tableHeader", tableHeader);
        object.put("content", array);
        return object;
    }

    /**
     * 接案介绍费
     *
     * @param param
     * @return
     */
    public JSONObject find_receivableInMxByExpense(JSONObject param) {
        JSONObject object = new JSONObject();
        JSONArray tableHeader = new JSONArray();
        Map DATE_OF_STATISTICS = MapUtil.mapper("field", "DATE_APPROVE",
                "headerName", "日期", "width", 110
        );
        tableHeader.add(DATE_OF_STATISTICS);
        Map GET_CAR_DEPT = MapUtil.mapper("field", "GET_CAR_DEPT",
                "headerName", "接案门店", "width", 90
        );
        tableHeader.add(GET_CAR_DEPT);
        Map GET_CAR_DEPT_NAME = MapUtil.mapper("field", "GET_CAR_DEPT_NAME",
                "headerName", "接案门店名称", "width", 200
        );
        tableHeader.add(GET_CAR_DEPT_NAME);
        Map CAR_LICENSE = MapUtil.mapper("field", "CAR_LICENSE",
                "headerName", "车牌", "width", 90
        );
        tableHeader.add(CAR_LICENSE);
        Map CASE_TYPE = MapUtil.mapper("field", "CASE_TYPE",
                "headerName", "案件类型", "width", 150
        );
        tableHeader.add(CASE_TYPE);
        Map SERVICE_DEPT_NAME = MapUtil.mapper("field", "SERVICE_DEPT_NAME",
                "headerName", "定损基地", "width", 120
        );
        tableHeader.add(SERVICE_DEPT_NAME);
        Map COMPANY_NAME = MapUtil.mapper("field", "COMPANY_NAME",
                "headerName", "定损公司", "width", 280
        );
        tableHeader.add(COMPANY_NAME);
        Map LOSS_QUOTATION_AMT = MapUtil.mapper("field", "LOSS_QUOTATION_AMT",
                "headerName", "定损金额", "width", 90, "sum", "true"
        );
        tableHeader.add(LOSS_QUOTATION_AMT);
        Map AMOUNT = MapUtil.mapper("field", "AMOUNT",
                "headerName", "收入金额", "width", 90, "sum", "true"
        );
        tableHeader.add(AMOUNT);
        Map SOURCE = MapUtil.mapper("field", "ID",
                "headerName", "来源单号", "width", 90, "cellRenderer", "dialogButton", "buttonList", "[\n" +
                        "                           {\n" +
                        "                           'id':'search',\n" +
                        "                           'name':'查详情',\n" +
                        "                           'hide':'false',\n" +
                        "                           'disabled':'false',\n" +
                        "                           'action': 'link',\n" +
                        "                           'link':'true'," +
                        "                           'api':'form/retail.order',\n" +
                        "                           'config':{'OAInterface':false,'api':'retail.order.findOne'}\n" +
                        "                           }]"
        );
        tableHeader.add(SOURCE);
        Map SOURCE_BUSINESS_TYPE = MapUtil.mapper("field", "SOURCE_BUSINESS_TYPE",
                "headerName", "来源单类型", "width", 120
        );
        tableHeader.add(SOURCE_BUSINESS_TYPE);
        Map ORIGIN = MapUtil.mapper("field", "ORIGIN",
                "headerName", "源单号", "width", 120
        );
        tableHeader.add(ORIGIN);
        Map ORIGIN_BUSINESS_TYPE = MapUtil.mapper("field", "ORIGIN_BUSINESS_TYPE",
                "headerName", "源单号类型", "width", 110
        );
        tableHeader.add(ORIGIN_BUSINESS_TYPE);

        Map ACCOUNTTYPE = MapUtil.mapper("field", "ACCOUNTTYPE",
                "headerName", "类型", "width", 90
        );
        tableHeader.add(ACCOUNTTYPE);
        JSONArray array = reportDaliyDao.find_receivableInMxByExpense(param);

        object.put("tableHeader", tableHeader);
        object.put("content", array);
//        JSONObject model =  SpringManager.getBean(MerchantReconciliationService.class).checkRequest(request);
        return object;
    }


    /**
     * 平台内客户
     *
     * @param param
     * @return
     */
    public JSONObject find_receivableInMxByVoucher(JSONObject param) {
        JSONObject object = new JSONObject();
        JSONArray tableHeader = new JSONArray();
        Map DATE_APPROVE = MapUtil.mapper("field", "DATE_APPROVE",
                "headerName", "日期", "width", 90
        );
        tableHeader.add(DATE_APPROVE);
        Map DEPT_ID = MapUtil.mapper("field", "DEPT_ID",
                "headerName", "门店编码", "width", 90
        );
        tableHeader.add(DEPT_ID);
        Map DEPT_NAME = MapUtil.mapper("field", "DEPT_NAME",
                "headerName", "门店", "width", 120
        );
        Map AMOUNT = MapUtil.mapper("field", "AMOUNT",
                "headerName", "总计", "sum", "true", "width", 80
        );
        tableHeader.add(AMOUNT);
        tableHeader.add(DEPT_NAME);
        Map ID = MapUtil.mapper("field", "ID",
                "headerName", "凭证号", "width", 70, "cellRenderer", "dialogButton", "buttonList", "[\n" +
                        "                           {\n" +
                        "                           'id':'search',\n" +
                        "                           'name':'详情',\n" +
                        "                           'hide':'false',\n" +
                        "                           'disabled':'false',\n" +
                        "                           'action': 'link',\n" +
                        "                           'link':'true'," +
                        "                           'api':'form/purch.voucher',\n" +
                        "                           'config':{'OAInterface':false,'api':'voucher.findOne'}\n" +
                        "                           }]"
        );
        tableHeader.add(ID);
        Map SOURCE = MapUtil.mapper("field", "SOURCE",
                "headerName", "源单据", "width", 130
        );
        tableHeader.add(SOURCE);
        Map CUSTOMER_ID = MapUtil.mapper("field", "CUSTOMER_ID",
                "headerName", "客户编码", "width", 90
        );
        tableHeader.add(CUSTOMER_ID);
        Map CUSTOMER_NAME = MapUtil.mapper("field", "CUSTOMER_NAME",
                "headerName", "客户", "width", 120
        );
        tableHeader.add(CUSTOMER_NAME);
        Map COMPANY_NAME = MapUtil.mapper("field", "COMPANY_NAME",
                "headerName", "公司", "width", 120
        );
        tableHeader.add(COMPANY_NAME);

        JSONArray array = reportDaliyDao.find_receivableInMxByVoucher(param);

        object.put("tableHeader", tableHeader);
        object.put("content", array);
//        JSONObject model =  SpringManager.getBean(MerchantReconciliationService.class).checkRequest(request);
        return object;
    }

    /**
     * 车险佣金
     *
     * @param param
     * @return
     */
    public JSONObject find_receivableInMxBycommission(JSONObject param) {
        JSONObject object = new JSONObject();
        JSONArray tableHeader = new JSONArray();
        Map DATE_APPROVE = MapUtil.mapper("field", "DATE_APPROVE",
                "headerName", "统计日期", "width", 110
        );
        Map AMOUNT = MapUtil.mapper("field", "AMOUNT",
                "headerName", "管理服务费", "sum", "true", "width", 150
        );
        tableHeader.add(DATE_APPROVE);
        Map PLATE_LICENSE = MapUtil.mapper("field", "PLATE_LICENSE",
                "headerName", "车牌号", "width", 90
        );
        Map VIN = MapUtil.mapper("field", "VIN",
                "headerName", "车架号", "width", 90
        );
        Map INSURANCE_TYPE = MapUtil.mapper("field", "INSURANCE_TYPE",
                "headerName", "险种类别", "width", 90
        );
        Map INSURANCE_AMOUNT = MapUtil.mapper("field", "INSURANCE_AMOUNT",
                "headerName", "保费金额", "width", 90);
        Map COMMISSION_TYPE = MapUtil.mapper("field", "COMMISSION_TYPE",
                "headerName", "佣金类型", "width", 90);
        Map DEPT_NAME = MapUtil.mapper("field", "DEPT_NAME",
                "headerName", "门店", "width", 120
        );

        tableHeader.add(AMOUNT);
        tableHeader.add(DEPT_NAME);
        tableHeader.add(PLATE_LICENSE);
        tableHeader.add(VIN);
        tableHeader.add(INSURANCE_TYPE);
        tableHeader.add(INSURANCE_AMOUNT);
        tableHeader.add(COMMISSION_TYPE);
        JSONArray array = reportDaliyDao.find_receivableInMxBycommission(param);

        object.put("tableHeader", tableHeader);
        object.put("content", array);
//        JSONObject model =  SpringManager.getBean(MerchantReconciliationService.class).checkRequest(request);
        return object;
    }

    /**
     * 货币资金（不含定损代收）
     *
     * @param request
     * @return
     */
    public Map payment(SimpleRequest request) throws ParseException {
        JSONObject param = this.checkRequest(request);
        JSONArray payment = null;
        if (param.size() > 0) {
            payment = reportDaliyDao.payment(param);
            payment.forEach(pay -> {
                JSONObject jsonObject = (JSONObject) pay;
                Object date_of_statistics = param.get("DATE_OF_STATISTICS");
                if (date_of_statistics != null && param.get("DATE_APPROVE") == null) {
                    jsonObject.put("DATE_OF_STATISTICS", date_of_statistics);
                }
                if (param.get("DATE_APPROVE") != null && date_of_statistics != null) {
                    try {
                        JSONArray date = (JSONArray) date_of_statistics;
                        JSONArray date_statistics = findRangeDateFromStartDateAndEndDate((String) param.get("DATE_APPROVE"),(String) date.get(0),(String) date.get(1),DateUtil.SHOW_DATETIME_UTC_FORMAT);

                        jsonObject.put("DATE_OF_STATISTICS", date_statistics);

                    } catch (Exception e) {

                        jsonObject.put("DATE_OF_STATISTICS", date_of_statistics);
                    }
                }

            });
        } else {
            JSONObject param1 = request.get("data");
            JSONObject param2 = new JSONObject();
            JSONArray array = new JSONArray();
            array.add(DateUtil.format(param1.getDate("reconcileBeginDate"), DateUtil.SHOW_DATETIME_UTC_FORMAT));
            array.add(DateUtil.format(param1.getDate("reconcileEndDate"), DateUtil.SHOW_DATETIME_UTC_FORMAT));
            param2.put("DATE_OF_STATISTICS", array);
            param2.put("COMPANY_ID", param1.getJSONObject("merchant").get("id").toString());
            payment = reportDaliyDao.payment(param2);
            payment.forEach(pay -> {
                JSONObject jsonObject = (JSONObject) pay;
                if (param2.get("DATE_OF_STATISTICS") != null) {
                    jsonObject.put("DATE_OF_STATISTICS", param2.get("DATE_OF_STATISTICS"));
                }
                if (param2.get("DATE_OF_STATISTICS") != null) {
                    try {
                        jsonObject.put("DATE_APPROVE", param2.get("DATE_OF_STATISTICS"));
                    } catch (Exception e) {
                        jsonObject.put("DATE_OF_STATISTICS", param2.get("DATE_OF_STATISTICS"));
                    }
                }

            });
        }
        return packageReturnArray(payment);
    }

    private JSONArray findRangeDateFromStartDateAndEndDate(String monthStr, String startStr, String endStr,String format) {
        JSONArray result = new JSONArray();
        Date month = DateUtil.parse(monthStr, DateUtil.SHOW_MONTH_FORMAT);

        Date start = reportDaliyDao.StringToDate(startStr,format);
        Date end = reportDaliyDao.StringToDate(endStr,format);
        if (month.after(start)){
            start = new Date(month.getTime());
        }else {
            start.setMonth(month.getMonth());
        }
        LocalDate localDate = DateUtil.UDateToLocalDate(month);
        LocalDate lastMonth = localDate.with(TemporalAdjusters.lastDayOfMonth());
        String s = lastMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        month = DateUtil.parse(s, DateUtil.SHOW_DATE_FORMAT);
        if (month.after(end)){
            end.setMonth(month.getMonth());
        }else {
            end = new Date(month.getTime());
        }
        result.add(DateUtil.format(start,format));
        result.add(DateUtil.format(end,format));
        return result;

    }

    public JSONObject paymentMx(SimpleRequest request) throws ParseException {
        JSONObject param = this.checkRequest(request);
        JSONObject object = new JSONObject();
        JSONArray tableHeader = new JSONArray();
        Map DATE_OF_STATISTICS = MapUtil.mapper("field", "DATE_APPROVE",
                "headerName", "统计日期", "width", 110
        );
        tableHeader.add(DATE_OF_STATISTICS);
        Map DEPT_NAME = MapUtil.mapper("field", "DEPT_NAME",
                "headerName", "部门名称", "width", 220
        );
        tableHeader.add(DEPT_NAME);

        Map TYPE = MapUtil.mapper("field", "PAYMENT_METHOD_TYPE_NAME",
                "headerName", "收款方式", "width", 90
        );
        tableHeader.add(TYPE);
        Map api = MapUtil.mapper("api", "rcl.businessAmt.paymentMxGdj");
        Map ZJ_AMT = MapUtil.mapper("field", "ZJ_AMT",
                "headerName", "货币资金（不含定损代收）", "width", 130, "sum", true, "cellRenderer", "link", "cellEditorParams", api
        );
        tableHeader.add(ZJ_AMT);
        Map AMOUNT = MapUtil.mapper("field", "AMOUNT",
                "headerName", "收款金额", "sum", "true", "width", 90
        );

        tableHeader.add(AMOUNT);
        Map DS_AMT = MapUtil.mapper("field", "DS_AMT",
                "headerName", "定损代收", "sum", "true", "width", 90
        );
        tableHeader.add(DS_AMT);

        Map COMPANY_NAME = MapUtil.mapper("field", "COMPANY_NAME",
                "headerName", "公司名称", "width", 280
        );
        tableHeader.add(COMPANY_NAME);

        JSONArray array = reportDaliyDao.paymentMx(param);

        object.put("tableHeader", tableHeader);
        object.put("content", array);
        return object;
    }


    /**
     * 货币资金（不含定损代收）_各单据
     *
     * @param request
     * @return
     */
    public JSONObject paymentMxGdj(SimpleRequest request) {
        JSONObject param = this.checkRequest(request);
        JSONObject object = new JSONObject();
        JSONArray tableHeader = new JSONArray();
        Map DATE_OF_STATISTICS = MapUtil.mapper("field", "DATE_OF_STATISTICS",
                "headerName", "日期", "width", 110
        );
        tableHeader.add(DATE_OF_STATISTICS);
        Map DEPT_ID = MapUtil.mapper("field", "DEPT_ID",
                "headerName", "门店", "width", 90
        );
        tableHeader.add(DEPT_ID);
        Map DEPT_NAME = MapUtil.mapper("field", "DEPT_NAME",
                "headerName", "门店名称", "width", 220
        );
        tableHeader.add(DEPT_NAME);
        Map SOURCE_ID = MapUtil.mapper("field", "ID",
                "headerName", "单号", "width", 90, "cellRenderer", "dialogButton", "buttonList", "[\n" +
                        "                           {\n" +
                        "                           'id':'search',\n" +
                        "                           'name':'',\n" +
                        "                           'hide':'false',\n" +
                        "                           'disabled':'false',\n" +
                        "                           'action': 'link',\n" +
                        "                           'link':'true'," +
                        "                           'api':'form/retail.order',\n" +
                        "                           'config':{'OAInterface':false,'api':'retail.order.findOne'}\n" +
                        "                           }]"
        );
        tableHeader.add(SOURCE_ID);
        Map ACCOUNTTYPE = MapUtil.mapper("field", "ACCOUNTTYPE",
                "headerName", "单据类型", "width", 90
        );
        tableHeader.add(ACCOUNTTYPE);
        Map CAR_LICENSE = MapUtil.mapper("field", "CAR_LICENSE",
                "headerName", "车牌", "width", 100
        );
        tableHeader.add(CAR_LICENSE);
//        Map MOBILE = MapUtil.mapper("field", "MOBILE",
//                "headerName", "手机号", "width", 120
//        );
//        tableHeader.add(MOBILE);
        Map AMOUNT = MapUtil.mapper("field", "AMOUNT",
                "headerName", "收款金额", "sum", "true", "width", 120
        );
        tableHeader.add(AMOUNT);
        Map PAYMENT_METHOD_TYPE_NAME = MapUtil.mapper("field", "PAYMENT_METHOD_TYPE_NAME",
                "headerName", "收款方式", "width", 90
        );
        Map COMPANY_NAME = MapUtil.mapper("field", "COMPANY_NAME",
                "headerName", "公司", "width", 280
        );
        tableHeader.add(COMPANY_NAME);
        tableHeader.add(PAYMENT_METHOD_TYPE_NAME);
        Map CUSTOMER_ID = MapUtil.mapper("field", "CUSTOMER_ID",
                "headerName", "客户编码", "width", 110
        );
        tableHeader.add(CUSTOMER_ID);
        Map CUSTOMER_NAME = MapUtil.mapper("field", "CUSTOMER_NAME",
                "headerName", "客户", "width", 220
        );
        tableHeader.add(CUSTOMER_NAME);
        Map CROSSIC_NAME = MapUtil.mapper("field", "CROSSIC_NAME",
                "headerName", "异业合作客户", "width", 220
        );
        tableHeader.add(CROSSIC_NAME);

        JSONArray array = reportDaliyDao.find_receivableInSKMxGdj(param);

        object.put("tableHeader", tableHeader);
        object.put("content", array);
        return object;
    }


    /**
     * 解析前端参数
     *
     * @param request
     * @return
     */
    public JSONObject checkRequest(SimpleRequest request) {
        JSONObject condition = (JSONObject) request.get("condition");
        List<Map> filters = (List<Map>) condition.get("filters");
        JSONObject model = new JSONObject();
        filters.forEach(filter -> {
            model.put((String) filter.get("field"), filter.get("value"));
        });
//        JSONObject jo = request.getJO();
//        if (jo.get("data")!=null&&jo.get("TJRQ")==null){
//            JSONObject jsonObject = (JSONObject) jo.get("data");
//            model.put("TJRQ",jsonObject.getJSONObject("node").getString("STATISTICS_DATE"));
//        }
        return model;
    }

    /***
     * 包装返回数据
     */
    private Map packageReturnArray(JSONArray array) {
        int size = array.size();
        return MapUtil.mapper(
                "content", array,
                "total", size,
                "size", size
        );
    }

    /**
     * 会员跨公司消费-收入
     *
     * @param request
     * @return
     */
    public Map findCrossCompanyIncome(SimpleRequest request) throws ParseException {
        JSONObject param = this.checkRequest(request);
        Object data = request.getJO().get("data");
        param.put("DATE_OF_STATISTICS", ((JSONObject) data).get("DATE_OF_STATISTICS"));
        return packageReturnArray(reportDaliyDao.findCrossCompanyIncome(param));
    }

    /**
     * 会员跨公司消费-支出
     *
     * @param request
     * @return
     */
    public Map findCrossCompanyPay(SimpleRequest request) throws ParseException {
        JSONObject param = this.checkRequest(request);
        return packageReturnArray(reportDaliyDao.findCrossCompanyPay(param));
    }

    /**
     * 兑换券补贴
     *
     * @param request
     * @return
     */
    public Map findPlatformSubsidy(SimpleRequest request) throws ParseException {
        JSONObject param = this.checkRequest(request);
        return packageReturnArray(reportDaliyDao.findPlatformSubsidy(param));
    }

    /**
     * 平台引流费用
     *
     * @param request
     * @return
     */
    public Map findPlatformFlowPay(SimpleRequest request) throws ParseException {
        JSONObject param = this.checkRequest(request);
        return packageReturnArray(reportDaliyDao.findPlatformFlowPay(param));
    }


    /**
     * 喷漆接收幅数
     *
     * @param request
     * @return
     * @throws ParseException
     */
    public Map find_receivePaint(SimpleRequest request) throws ParseException {
        JSONObject param = this.checkRequest(request);
        //把SQL写进去
        JSONArray payment = reportDaliyDao.find_receivePaint(param);
        payment.forEach(pay -> {
            JSONObject jsonObject = (JSONObject) pay;
            if (param.get("DATE_OF_STATISTICS") != null && param.get("DATE_APPROVE") == null) {
                jsonObject.put("DATE_OF_STATISTICS", param.get("DATE_OF_STATISTICS"));
            }
            if (param.get("DATE_APPROVE") != null && param.get("DATE_OF_STATISTICS") != null) {
                try {
                    new SimpleDateFormat("yyyy-MM-dd").parse((String) param.get("DATE_APPROVE"));
                    jsonObject.put("DATE_APPROVE", param.get("DATE_APPROVE"));

                } catch (Exception e) {

                    jsonObject.put("DATE_OF_STATISTICS", param.get("DATE_OF_STATISTICS"));
                }
            }

        });
        return packageReturnArray(payment);
    }

    /**
     * 喷漆发起幅数
     *
     * @param request
     * @return
     * @throws ParseException
     */
    public Map find_initPaint(SimpleRequest request) throws ParseException {
        JSONObject param = this.checkRequest(request);
        //把SQL写进去
        JSONArray payment = reportDaliyDao.find_initPaint(param);
        payment.forEach(pay -> {
            JSONObject jsonObject = (JSONObject) pay;
            if (param.get("DATE_OF_STATISTICS") != null && param.get("DATE_APPROVE") == null) {
                jsonObject.put("DATE_OF_STATISTICS", param.get("DATE_OF_STATISTICS"));
            }
            if (param.get("DATE_APPROVE") != null && param.get("DATE_OF_STATISTICS") != null) {
                try {
                    new SimpleDateFormat("yyyy-MM-dd").parse((String) param.get("DATE_APPROVE"));
                    jsonObject.put("DATE_APPROVE", param.get("DATE_APPROVE"));

                } catch (Exception e) {

                    jsonObject.put("DATE_OF_STATISTICS", param.get("DATE_OF_STATISTICS"));
                }
            }

        });
        return packageReturnArray(payment);
    }


    /**
     * 查询喷漆接收明细
     *
     * @param request
     * @return
     */
    public JSONObject find_receivePaintMX(SimpleRequest request) throws ParseException {
        JSONObject param = request.getJO().getJSONObject("data").getJSONObject("node");
        JSONObject object = new JSONObject();
        JSONArray tableHeader = new JSONArray();

        //field 改成字段名
        Map servicePlan = MapUtil.mapper("field", "ID",
                "headerName", "服务方案", "width", 220
        );
        tableHeader.add(servicePlan);

        tableHeader.add(MapUtil.mapper("field", "CAR_LISCENCE",
                "headerName", "车牌", "width", 220
        ));

        tableHeader.add(MapUtil.mapper("field", "REALNAME",
                "headerName", "车主", "width", 220
        ));


        tableHeader.add(MapUtil.mapper("field", "PICK_DEPT",
                "headerName", "接车门店", "width", 220
        ));


        tableHeader.add(MapUtil.mapper("field", "INNER_DEPT",
                "headerName", "内协门店", "width", 220
        ));


        tableHeader.add(MapUtil.mapper("field", "PRODUCT_NAME",
                "headerName", "商品名称", "width", 220
        ));


        tableHeader.add(MapUtil.mapper("field", "SALE_QTY",
                "headerName", "数量", "width", 220
        ));


        tableHeader.add(MapUtil.mapper("field", "SPECIFICATIONS",
                "headerName", "规格", "width", 220
        ));


        tableHeader.add(MapUtil.mapper("field", "PRICE_UNIT",
                "headerName", "销售单价", "width", 220
        ));


        tableHeader.add(MapUtil.mapper("field", "PFT_PRICE_UNIT",
                "headerName", "优惠单价", "width", 90
        ));


        tableHeader.add(MapUtil.mapper("field", "REFER_TAX",
                "headerName", "参考成本价", "width", 120
        ));


        tableHeader.add(MapUtil.mapper("field", "FINISH_DATE",
                "headerName", "完工时间", "width", 180
        ));


        JSONArray array = reportDaliyDao.find_receivePaintMX(param);
        object.put("tableHeader", tableHeader);
        object.put("content", array);
        return object;
    }

    /**
     * 查询喷漆发起明细
     *
     * @param request
     * @return
     */
    public JSONObject find_receiveInitMX(SimpleRequest request) throws ParseException {
        JSONObject param = request.getJO().getJSONObject("data").getJSONObject("node");
        JSONObject object = new JSONObject();
        JSONArray tableHeader = new JSONArray();

        //field 改成字段名
        Map servicePlan = MapUtil.mapper("field", "ID",
                "headerName", "服务方案", "width", 220
        );
        tableHeader.add(servicePlan);

        tableHeader.add(MapUtil.mapper("field", "CAR_LISCENCE",
                "headerName", "车牌", "width", 220
        ));

        tableHeader.add(MapUtil.mapper("field", "REALNAME",
                "headerName", "车主", "width", 220
        ));


        tableHeader.add(MapUtil.mapper("field", "PICK_DEPT",
                "headerName", "接车门店", "width", 220
        ));


        tableHeader.add(MapUtil.mapper("field", "INNER_DEPT",
                "headerName", "内协门店", "width", 220
        ));


        tableHeader.add(MapUtil.mapper("field", "PRODUCT_NAME",
                "headerName", "商品名称", "width", 220
        ));


        tableHeader.add(MapUtil.mapper("field", "SALE_QTY",
                "headerName", "数量", "width", 220
        ));


        tableHeader.add(MapUtil.mapper("field", "SPECIFICATIONS",
                "headerName", "规格", "width", 220
        ));


        tableHeader.add(MapUtil.mapper("field", "PRICE_UNIT",
                "headerName", "销售单价", "width", 220
        ));


        tableHeader.add(MapUtil.mapper("field", "PFT_PRICE_UNIT",
                "headerName", "优惠单价", "width", 90
        ));


        tableHeader.add(MapUtil.mapper("field", "REFER_TAX",
                "headerName", "参考成本价", "width", 120
        ));

        tableHeader.add(MapUtil.mapper("field", "FINISH_DATE",
                "headerName", "完工时间", "width", 180
        ));

        JSONArray array = reportDaliyDao.find_initPaintMX(param);
        object.put("tableHeader", tableHeader);
        object.put("content", array);
        return object;
    }


}
